0

尝试使用 Numberformatter 解析和验证用户输入的整数(格式化程序类型 = DECIMAL)。也许它是学术性的,但我希望能够将分组分隔符更改为与语言环境中设置的约定不同。例如,在美国,分组分隔符(“千位分隔符”)默认为逗号 (',')。更改分组分隔符会产生一些意想不到的结果(请参阅下面的单元测试代码)。我不确定格式化程序是否根本不会做我想做的事或者我做错了(例如格式化程序类型是否应该= PATTERN_DECIMAL)。如果格式化程序类型应该是 PATTERN_DECIMAL,那么某处是否有可用的文档?ICU 文档......嗯......没有它可能的帮助。

$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));

}
4

1 回答 1

1

分隔符是符号,而不是属性。见下Predefined constants

使用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
于 2019-06-21T15:30:42.203 回答