Author: laruence
Original address: http://www.laruence.com/2013/03/26/2884.html
About the floating-point number of PHP, I've written an article before: What you should know about PHP floating-point numbers (all ' bogus ' on the float in PHP)
However, I missed a point, which is the answer to the following FAQ:
- <?php
- $f = 0.58;
- var_dump(intval($f * )); //Why output
- ?>
Why is the output 57? PHP bug?
I believe that a lot of students have had this kind of doubt, because the light asks me the similar question person to be many, not to mention bugs.php.net often people ask ...
To understand this, first we need to know the representation of floating-point numbers (IEEE 754):
Floating-point numbers, in the case of a 64-bit length (double), take the 1-bit sign bit (E), 11 exponent (Q), and 52-bit mantissa (M) (altogether 64 bits).
Sign bit: The highest bit represents the positive or negative of the data, 0 is a positive number, and 1 indicates a negative number.
Digits: Indicates that the data is a power of 2, and the exponent is represented by an offset code
Mantissa: A valid number that represents the decimal point of the data.
Here is the key point is that the decimal in the binary representation, about how to use binary decimal notation, you can Baidu, I do not repeat here, we key to understand, 0.58 for the binary representation, is an infinitely long value (the following number omitted the implied 1):
- The binary representation of 0.58 is basically (52 bits) is: 0010100011110101110000101000111101011100001010001111
- The binary representation of 0.57 is basically (52 bits) is: 0010001111010111000010100011110101110000101000111101
and the binary of both, if only through the 52-bit calculation, respectively:
- 0.58-0.57999999999999996
- 0.57-0.56999999999999995
As for the 0.58 * 100 of the specific floating-point multiplication, we do not consider so thin, interesting to see (floating point), we are vague in mental arithmetic to see ... 0.58 * 100 = 57.999999999
Then you intval, Nature is 57 ....
Visible, the key point of this problem is: " you seem to have a poor decimal, in the computer binary representation is infinite "
So, do not think this is a PHP bug, this is the case .....
Go A FAQ for PHP floating-point numbers