Home > Article > Backend Development > Questions about PHP and js floating point operations
Why is 0.1 + 0.2 not equal to 0.3? (Correct result: 0.30000000000000004)
Why is 0.8 * 7 not equal to 5.6? (Correct result: 5.6000000000000005)
var_dump(intval(0.58 * 100));
The correct result is 57, not 58
In fact, these results are not language bugs, but are related to the implementation of the language The principle is related. All numbers in js are unified as Number, including integers. In fact, all numbers are of double type.
And PHP will distinguish between int and float. No matter what language, as long as floating point operations are involved, there are similar problems, so you must pay attention when using them.
According to the international standard IEEE 754, any binary floating point number V can be expressed in the following form:
V = (-1)s * M * E 1. (-1)s 表示符号位,当s=0,V为正数;当s=1,V为负数。 2. M表示有效数字,大于等于1,小于2。 3. 2E 表示指数位。
For example: decimal -5.0 , written in binary is -101.0, which is equivalent to -1.01×22. Then, s=1, M=1.01, E=2.
IEEE 754 stipulates that for a 32-bit floating point number, the highest 1 bit is the sign bit s, the next 8 bits are the exponent E, and the remaining 23 bits are the significant digit M.
For a 64-bit floating point number, the highest 1 bit is the sign bit S, the next 11 bits are the exponent E, and the remaining 52 bits are the significant digit M.
IEEE 754 also has some special provisions for the significant digit M and the exponent E.
As mentioned before, 1≤Me9078eed89a12476e874fb193db17ca3
The above is the detailed content of Questions about PHP and js floating point operations. For more information, please follow other related articles on the PHP Chinese website!