PHP manual says:
A rational number that can be accurately represented in decimal, such as 0.1 or 0.7, cannot be converted to a binary format without losing a little bit of precision, regardless of how many of the mantissa can be accurately represented by the binary used internally.
// example1$float = (0.1 + 0.7) * 10;echo (integer) $float; // 7echo floor($float); // 7// example2echo (integer) (1.5+1.5); // 3echo floor(1.5+1.5); // 3// example3echo (integer) (0.5*10); // 5echo floor(0.5*10); // 5
Why in Example 2 and Example 3, floating-point numbers 加 and 乘 operations can preserve precision?
Reply content:
PHP manual says:
A rational number that can be accurately represented in decimal, such as 0.1 or 0.7, cannot be converted to a binary format without losing a little bit of precision, regardless of how many of the mantissa can be accurately represented by the binary used internally.
// example1$float = (0.1 + 0.7) * 10;echo (integer) $float; // 7echo floor($float); // 7// example2echo (integer) (1.5+1.5); // 3echo floor(1.5+1.5); // 3// example3echo (integer) (0.5*10); // 5echo floor(0.5*10); // 5
Why in Example 2 and Example 3, floating-point numbers 加 and 乘 operations can preserve precision?
It's time to present my blog again:
- Code Puzzle (iv)-floating point (from surprise to thinking)
- Code Puzzle (v)-floating point number (who stole your accuracy?) )
0.1 + 0.7The result is0.7999999999999999
0.51.5you can use floating-point numbers for precise representations.
0.1The binary:
符号位 0 指数 01111011 (-4)位数 1.10011001100110011001101 (1.60000002384185791015625)
Put this number back in decimal:0.10000000149011612
0.7The binary:
符号位 0 指数 01111110 (-1)位数 1.01100110011001100110011 (1.39999997615814208984375)
Put this number back in decimal:0.699999988079071