Answers to frequently asked questions a PHP floating point numbers

However, I was missing the point, which is this FAQ for the following answer:
<?php
$f = 0.58;
var_dump (intval ($ f * 100)); // why the output 57
?>
Why output is 57 ah? PHP bug in it?
I believe that many of the students have had such a question, because I asked the light on a lot of people with similar problems, not to mention the bugs.php.net often asked ...
Wants to understand this reason, we need to know the floating-point representation (IEEE 754):
Floating-point, 64-bit length (double), for example, will use a sign bit (E), 11 exponent bits (Q), 52-bit mantissa (M) represented by (total 64).
Sign bit: the maximum data bit indicates positive or negative, 0 for positive, 1 for negative.
Index bits: data indicative of a power base 2, using the index code indicates the offset
Mantissa: significant figures after the decimal point data.
The key point here is that the decimal representation of the binary, decimal on how to use the binary representation, we can look at Baidu, I will not repeat them here, we have the key to understanding 0.58 for binary representation, it is of infinite value (following figure 1 implicit omitted) ..
0.58 substantially binary representation (52) is: 0010100011110101110000101000111101011100001010001111
0.57 substantially binary representation (52) is: 0010001111010111000010100011110101110000101000111101
Both binary and, if this is only by 52 if calculated, they are:
0.58 -> 0.57999999999999996
0.57 -> 0.56999999999999995
As for the specific floating point multiply 0.58 * 100, we do not consider so fine, are interested can see (Floating point), we look at mental arithmetic to blur ... 0.58 * 100 = 57.999999999
Then you look intval, naturally it is a ... 57.
Visible, the key point of this question is: "You seem finite decimal, binary computer actually represents is infinite."
so, I do not think that this is a bug in PHP, which is this ... ..
Be the First to comment.

Guess you like

Origin blog.csdn.net/wccczxm/article/details/89379130