Home >Backend Development >PHP Tutorial >Comparison example analysis of two float (floating point numbers) in PHP_php skills
The example in this article describes two float (floating point number) comparison methods in PHP. Share it with everyone for your reference. The details are as follows:
When I was developing a contract management system recently, it involved comparing two floating point numbers, which made me very depressed.
A long time ago, I didn’t know where I heard the “truth” of “Don’t use the equal sign to compare floating point numbers”. I used it on a daily basis, and it seemed that there was no problem. But this time the problem finally came.
<?php $sum = "12300.00"; $a = "10000.30"; $b = "2000.30"; $c = "299.40"; $sum = (float) $sum; $s = (float) ($a+$b+$c); var_dump($sum, $s); var_dump($sum==$s);
The result is:
float(12300)
float(12300)
bool(false)
I later learned that in PHP, to compare the sizes of two floating point numbers, you can use bccomp (parameter 1, parameter 2, decimal places) to compare.
<?php $sum = "12300.00"; $a = "10000.30"; $b = "2000.30"; $c = "299.40"; $sum = (float) $sum; $s = (float) ($a+$b+$c); var_dump($sum, $s); var_dump(bccomp($sum,$s,2));
Result:
float(12300)
float(12300)
int(0) // 0 means two floating point values are equal
For specific usage of the bccomp function, please refer to the PHP manual.
I hope this article will be helpful to everyone’s PHP programming design.