Home >Backend Development >PHP Problem >PHP floating point subtraction is not equal to 0
php floating point subtraction is not equal to 0
php floating point subtraction is not equal to 0 because the computer When decimal numbers are converted to binary numbers, precision is lost, so the bcadd() function can be used to add and subtract floating point numbers and perform precision conversion.
In addition, to determine whether a floating point number is equal to 0, we do not use $num == 0, but abs($d) < EPS. This EPS is a very small value.
As floating-point data, part of its accuracy has been lost and cannot be completely accurate. So never trust that a floating-point number result is accurate to the last digit, and never compare two floating-point numbers for equality. It should be noted that this is not a problem with PHP, but a problem with the computer's internal processing of floating point numbers! The same problem will be encountered in languages such as C and JAVA.
An example of floating point number calculation is as follows:
$a = 0.2+0.7; $b = 0.9; var_dump($a == $b);
The printed result is: bool(false). In other words, the calculation result of 0.2 0.7 here is not equal to 0.9, which is obviously against our common sense.
Regarding this issue, the official PHP manual once stated: Apparently a simple decimal fraction such as 0.2 cannot be converted to an internal binary format without losing a little precision. This has to do with the fact that it is impossible to express certain decimal fractions exactly with a finite number of digits. For example, 1/3 in decimal becomes 0.3333333….
So to compare two floating point numbers, we need to control them within the precision range we need before comparing, so use the bcadd() function to add the floating point numbers and convert the precision (to a string) :
var_dump(bcadd(0.2,0.7,1) == 0.9); // 输出:bool(true)
For more PHP related knowledge, please visit PHP Chinese website!
The above is the detailed content of PHP floating point subtraction is not equal to 0. For more information, please follow other related articles on the PHP Chinese website!