numfmt_format_currency(new NumberFormatter('en',2), 31.005, "USD")
This code outputs $31.00. But it should output $31.01. How to resolve this issue??? This code prints $31.00. But $31.01 should be output. how to solve this problem? ?
PHP ignores the conversion of 0.005 to 0.01 in price format.
I tried to fix Magento's currency formatting issue but found a problem with PHP
31.005 is actually between the two numbers, see floating point precision at https://php.net/float.
(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.
##
This is what droopsnoot commented Number formatting default mode and creation As Olivier reminded in the comments, the default mode is semi-even rounding, also known as banker's rounding. At the same time, they pointed out that it would be "more formal" to use the class constant NumberFormatter::CURRENCY instead of using magic number 2This 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.