Home>

### php - regarding misalignment of ieee754 floating point arithmetic standard

For the first time today, for the first time in the online industry for 15 years
I learned that JavaScript cannot calculate decimals

Example
I want 30,000 yen + consumption tax (8%)
An extremely simple formula that seems to be common

``alert (30000 * 1.08);``

The calculation result is of course ¥ 32,400

But

The result of JavaScript is "32400.000000000004"

This is JavaScript
I found thebugspecification for compliance with the IEEE754 floating point arithmetic standard

And here is the question
It is said that not only JavaScript but also PHP is compliant with IEEE754

http://php.net/manual/en/language.types.float.php

The precision of floating point numbers is finite. Depending on the system, PHP normally uses the IEEE 754 double-precision format. This format introduces errors in rounding on the order of 1.11e-16. If i do complex arithmetic, the error will be even greater. And of course, errors must be taken into account when combining several operations.

In addition, rational numbers that can be represented in decimal numbers with an exact decimal number, such as 0.1 and 0.7, cannot be represented exactly as binary floating-point numbers. This is the same no matter how large the mantissa is. Therefore, when converting it to an internal binary representation, the accuracy is inevitably reduced. As a result, it can cause strange results. For example, the result of floor ((0.1 + 0.7) * 10) will usually be 7. Perhaps i am expecting 8, but that is not the case. This is because the internal value of this calculation is 7.9999999999999991118 ...

So don't trust the last digit of the decimal, and don't compare the decimals directly to see if they are equal. If i need higher precision, use an arbitrary precision math function or the gmp function instead.

The same calculation with PHP (5.3.3) as a trial

``echo 30000 * 1.08;``

The result seemed to be a normal value of "32400" (is the same result as a general calculator more accurate?)

What is the difference between PHP and JavaScript?
Is the IEEE754 compliance ambiguous?

Please tell me who i am busy, but understand

When I did the same calculation in PHP (5.3.3), the result seemed to be a normal value of "32400" (is the same result as a general calculator more accurate?)

It'slooks only. In fact,`var_dump (30000 * 1.08 === 32400.0);`will display`bool (FALSE)`(3v4l).