P粉2758839732023-08-09 10:40:33
31.005 is actually between the two numbers, see floating point precision at https://php.net/float.
> ini_set('precision', 23) = "14" > 31.005 = 31.00499999999999900524
(In PHP and other languages, there is no number 31.005..)
You need to provide numbers with sufficient precision, but with as little error as possible, to match your display requirements. This can be achieved by specifying the rounding mode, for example, if you want to round 31.005 to 31.01, you can choose to round up or round down.
$formatter = new NumberFormatter('en', NumberFormatter::CURRENCY);
$formatter->setAttribute(
NumberFormatter::ROUNDING_MODE,
NumberFormatter::ROUND_HALFUP
);
echo $formatter->formatCurrency(31.005, 'USD'), "\n";
# Output: .01
This is what droopsnoot commentedNumber formatting default mode and creation
$formatter = new NumberFormatter('en', 2);
$formatter = new NumberFormatter('en', NumberFormatter::CURRENCY);
This will allow your code to communicate better, otherwise the number 2 might be interpreted as the number of digits or precision, but that is not the case in this case. You can find all style constants in the PHP manual. Note: This is not just a PHP specific problem, you will encounter the same problem when you pass these numbers to Javascript and need to format them in Javascript.