Php 看看我是否误解了numberformatter,或者我是否错误地使用它进行解析和验证
尝试使用Numberformatter解析和验证用户输入的整数(格式化程序类型=十进制)。也许这是学术性的,但我希望能够将分组分隔符更改为不同于区域设置中设置的约定。例如,在美国,分组分隔符(“千位分隔符”)默认为逗号(“,”)。更改分组分隔符会产生一些意外的结果(请参见下面的单元测试代码)。我不确定格式化程序是否只是不执行我想要的操作,或者我是否做错了(例如,格式化程序类型是否应=PATTERN\u DECIMAL)。如果格式化程序类型应为PATTERN_DECIMAL,是否有可用的文档?ICU文件是……嗯。。。这可能没什么帮助Php 看看我是否误解了numberformatter,或者我是否错误地使用它进行解析和验证,php,parsing,grouping,separator,numberformatter,Php,Parsing,Grouping,Separator,Numberformatter,尝试使用Numberformatter解析和验证用户输入的整数(格式化程序类型=十进制)。也许这是学术性的,但我希望能够将分组分隔符更改为不同于区域设置中设置的约定。例如,在美国,分组分隔符(“千位分隔符”)默认为逗号(“,”)。更改分组分隔符会产生一些意外的结果(请参见下面的单元测试代码)。我不确定格式化程序是否只是不执行我想要的操作,或者我是否做错了(例如,格式化程序类型是否应=PATTERN\u DECIMAL)。如果格式化程序类型应为PATTERN_DECIMAL,是否有可用的文档?IC
$this->frmtr = new \NumberFormatter('en-US', NumberFormatter::DECIMAL)
function testGroupingSeparator() {
$expectedResult = 12345;
$this->assertEquals($expectedResult, $this->frmtr->parse("12,345", NumberFormatter::TYPE_INT64));
// you can change the grouping separator character
$newChar = '/';
$this->frmtr->setTextAttribute(NumberFormatter::GROUPING_SEPARATOR_SYMBOL, $newChar);
$this->assertEquals($newChar, $this->frmtr->getTextAttribute(NumberFormatter::GROUPING_SEPARATOR_SYMBOL));
// but it appears to have no effect on parsing....the newly set grouping character is treated as 'trailing debris'
$expectedResult = 12;
$this->assertEquals($expectedResult, $this->frmtr->parse("12/345", NumberFormatter::TYPE_INT64));
// semi-colon appears not to work at all as a grouping separator
$newChar = ';';
$this->frmtr->setTextAttribute(NumberFormatter::GROUPING_SEPARATOR_SYMBOL, $newChar);
$this->assertFalse($this->frmtr->parse("12;345", NumberFormatter::TYPE_INT64));
// it also impacts formatting but in a really odd and unexpected way
$expectedResult = '12,345.';
$this->assertEquals($expectedResult, $this->frmtr->format(12345, NumberFormatter::TYPE_INT64));
// ok, let's set it back to 'normal'
$this->frmtr->setTextAttribute(NumberFormatter::GROUPING_SEPARATOR_SYMBOL, ',');
// you can change whether grouping is used
$this->frmtr->setAttribute(NumberFormatter::GROUPING_USED, false);
// now the parser will treat the grouping separator as trailing debris which is OK but unexpected perhaps
$expectedResult = 12;
$this->assertEquals($expectedResult, $this->frmtr->parse("12,345", NumberFormatter::TYPE_INT64));
// and the formatting gets screwed up in a weird way with the grouping separator placed at the end
$expectedResult = '12345,';
$this->assertEquals($expectedResult, $this->frmtr->format(12345, NumberFormatter::TYPE_INT64));
}
分隔符是符号,而不是属性。看下面 使用
setSymbol
而不是setTextAttribute
,应该得到预期的结果,例如:
$frmtr = new \NumberFormatter('en-US', NumberFormatter::DECIMAL);
$frmtr->setSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL, '/');
print $frmtr->format("12345", NumberFormatter::TYPE_INT64) . "\n";
print $frmtr->parse("12/345", NumberFormatter::TYPE_INT64) . "\n";
产出:
12/345
12345