I am trying to write a general purpose function for formatting decimal numbers that works with any number of decimals — honoring the original number of decimals and current locale (which can be set to any that the local enviroment supports).
This is what I have (in a test):
setlocale(LC_MESSAGES, 'en_US');
$formatter = new \NumberFormatter('en_US', \NumberFormatter::DECIMAL);
$num = 1234.56789;
$this->assertEquals('1,234.56789', $formatter->format($num, \NumberFormatter::TYPE_DOUBLE));
... but it will fail:
Failed asserting that two strings are equal.
Expected :'1,234.56789'
Actual :'1,234.568'
By adding this line:
echo 'MAX_FRACTION_DIGITS: '. $formatter->getAttribute(\NumberFormatter::MAX_FRACTION_DIGITS) . PHP_EOL;
... I was able to determine that by default NumberFormatter rounds the number to 3 digits.
Setting a large number for MAX_FRACTION_DIGITS like so:
$formatter->setAttribute(\NumberFormatter::MAX_FRACTION_DIGITS, 100);
... will get me what I want, but I am sure I am missing something.
Is there a less hacky way to do what I want?