Home  >  Article  >  Backend Development  >  PHP floating point number comparison method

PHP floating point number comparison method

尚
forward
2020-03-25 09:20:513999browse

PHP floating point number comparison method

There is a saying in the PHP manual: Never compare two floating point numbers for equality.

The way the computer handles floating-point numbers internally determines that floating-point numbers cannot be 100% accurate, so precision loss will occur when processing floating-point numbers. For example, the following program:

<?php  
$a   =   15521.42;  
$b   =   15480.3;  
$c = $a-$b;  
var_dump($c);    //php4:float(41.120000000001)   php5:float(41.12)   
var_dump($c == 41.12);     //bool(false)   
?>

The first output statement: The output $c under PHP4 may be 41.120000000001, or similar results, and the following 1 is part of the precision loss. Some "optimizations" have been made to this problem in PHP5, so that the inaccurate part will not be displayed in the output results, but at the same time, we will ignore this problem and think that $c==41.12.

The second output statement: false will be output in PHP4 and PHP5.

Disclaimer: 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 C/JAVA.

Extension: We also cannot use >, 95ec6993dc754240360e28e0de8de30a= or <=

So, how should we compare two floating point numbers for equality?

After reading the above introduction, we know: there is no way to accurately compare two floating point numbers for equality! So... we can only compare within the accuracy range we want (for example, in the above example, we only need to compare $c to be equal to 41.12 within two decimal places).

The following is an example from the PHP manual comments

nction floatcmp($f1,$f2,$precision = 10) {// are 2 floats equal   
    $e = pow(10,$precision);  
    $i1 = intval($f1 * $e);  
    $i2 = intval($f2 * $e);  
    return ($i1 == $i2);  
}  
function floatgtr($big,$small,$precision = 10) {// is one float bigger than another   
    $e = pow(10,$precision);  
    $ibig = intval($big * $e);  
    $ismall = intval($small * $e);  
    return ($ibig > $ismall);  
}  
function floatgtre($big,$small,$precision = 10) {// is on float bigger or equal to another   
    $e = pow(10,$precision);  
    $ibig = intval($big * $e);  
    $ismall = intval($small * $e);  
    return ($ibig >= $ismall);  
}


   

Related recommendations:

PHP video tutorial:https://www.php.cn/course/list/29/type/2.html

The above is the detailed content of PHP floating point number comparison method. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:oschina.net. If there is any infringement, please contact admin@php.cn delete