Home > Article > Backend Development > PHP floating point comparison method_php tips
The example in this article describes the method of PHP floating point comparison. Share it with everyone for your reference, the details are as follows:
<?php /** * 浮点数一般是不能用来比较大小的,但是我们可以用一种变通的的方式 * 用var_dump输出浮点是看不出效果的,可以用serialize查看 * 1.round 2.浮点转换成字符串 * * 转换成字符串方法: * 通过在其前面加上(string)或用strval()函数来转变成 字符串 * 在一个需要字符串的表达式中,字符串会自动转变,比如在使用函数 echo() 或 print() 时, 或在一个变量和一个 字符串 进行比较时,就会发生这种转变 * true会转为1 , 而false则会转为空字符串 * */ $a = 13.2; $b = 24; $c = $a/$b; //实际值是这个d:0.54999999999999993338661852249060757458209991455078125; echo serialize($c).'<br/>';// echo $c.'<br/>';//输出时会显示成0.55 实际的值是比他小的 //所以直接和0.55比较大小是不成立的 if($c == 0.55){ echo 'nothing'; } $c = round($c,2); //用round处理 if($c == 0.55){ echo 'ok'; } echo "<br/>"; //强制转为字符串 // $c = (string)$c; // $c = strval($c); if("$c" == 0.55){ echo 'ok'; } ?>
The running results are as follows:
d:0.54999999999999993338661852249060757458209991455078125; 0.55 ok ok
Readers who are interested in more PHP-related content can check out the special topics on this site: "Summary of PHP operations and operator usage", "Introduction to PHP basic syntax tutorial", " Summary of PHP error and exception handling methods" and "Summary of common PHP functions and techniques"
I hope this article will be helpful to everyone in PHP programming.