PHP floating point subtraction is not equal to 0

angryTom
Release: 2023-02-27 20:02:02
Original
3581 people have browsed it

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);
Copy after login

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)
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template