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