PHP floating point operations-related issues

php and rounding floating-point calculation and comparison inaccurate. For example:
$a = 0.2+0.7;
$b = 0.9;
var_dump ($ a == $ b); // result is output bool (false)
Official PHP manual explains: Obviously that simple decimal fractions like 0.2 can not be converted into internal binary format without a little loss of precision. 
 printf ( "% 0.20f", $ a); // result is output .89999999999999991118
 printf ( "% 0.20f", $ b); // result is output .90000000000000002220
The results indicate that, as a floating-point data, the accuracy of which has lost part not to be completely accurate. So never trust floating number results to the last digit, and never compare floating point numbers for equality.
It should be noted that this is not a PHP problem, but the problem of floating point internal processing computer! Will encounter the same problems in C, JAVA and other languages.
Solution: it needs to be controlled within the range of accuracy we need to re-compare.
Thus using bcadd () function to want to add floating-point precision conversion and (a string):
var_dump (bcadd (0.2,0.7,1) == 0.9); // result is outputted bool (true)
Use may also be round () function is rounded to the precision specified:
var_dump (round (0.2 + 0.7,2) == 0.9); // result is outputted bool (true)
 
 

Guess you like

Origin www.cnblogs.com/rxbook/p/11402224.html