Search code examples
phpcurrencynumberformatter

Why does NumberFormatter drop monetary fraction digits in format()


Why do the following two lines

$fmt = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
echo $fmt->format(12.34, NumberFormatter::CURRENCY);

output $12.00 ?


Solution

  • It's because you're using the NumberFormatter::CURRENCY constant as the second argument to format().

    In the predefined constants section of the NumberFormatter documentation, the constants are grouped under which methods they should be used with.

    NumberFormatter::CURRENCY has a value of 2 and should be used when constructing the formatter, as you have done. A value of 2 in the format() function corresponds to NumberFormatter::TYPE_INT64.

    You should just be able to call format(12.34) without a second argument.

    $fmt = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
    echo $fmt->format(12.34);