There is a sentence in the PHP manual:Never compare two floating point numbers for equality.
I didn't care too much in the past. I recently fell into the project because of this problem, so I kept it in mind.
The internal processing of floating point numbers in the computer determines that the floating point number cannot be 100% accurate. Therefore, when dealing with floating point operations, the loss of precision may occur. For example, the following program:
5 |
var_dump( $c ); //php4:float(41.120000000001) php5:float(41.12) |
6 |
var_dump( $c
== 41.12); //bool(false) |
The first output statement: $ c output in PHP4 may be 41.120000000001, or a similar result. The following 1 is part of the loss of precision. In PHP5, we made some "optimizations" on this issue, and the output results won't show inaccurate parts, but at the same time, we will ignore this issue and think that $ c = 41.12.
The second output statement: false is output in both PHP4 and PHP5.
Note: This is not a PHP issue, but a problem where the computer processes floating point numbers! The same problem occurs in C \ JAVA. For more information, see Go-deep-dive floating point number.
For more information, see >,<>=or <=.
So how can we compare two floating point numbers to be equal?
After reading the above introduction, we will know that there is no way to accurately compare two floating point numbers equal! So... we can only compare within the range of precision we want (for example, in the above example, we only need to compare $ c within two decimal places equals 41.12 ).
The following is an example in the PHP manual comment (it is good to read more about the manual ~~) :
01 |
function floatcmp( $f1 , $f2 , $precision
= 10) // are 2 floats equal |
03 |
$e = pow(10, $precision ); |
04 |
$i1 =
intval ( $f1
* $e ); |
05 |
$i2 =
intval ( $f2
* $e ); |
09 |
function floatgtr( $big , $small , $precision
= 10) // is one float bigger than another |
11 |
$e = pow(10, $precision ); |
12 |
$ibig =
intval ( $big
* $e ); |
13 |
$ismall =
intval ( $small
* $e ); |
14 |
return ( $ibig
> $ismall ); |
17 |
function floatgtre( $big , $small , $precision
= 10) // is on float bigger or equal to another |
19 |
$e = pow(10, $precision ); |
20 |
$ibig =
intval ( $big
* $e ); |
21 |
$ismall =
intval ( $small
* $e ); |
22 |
return ( $ibig
>= $ismall ); |