This example describes two float (floating-point) comparison methods in PHP. Share to everyone for your reference. Specifically as follows:
In the recent development of a contract management system, involving two floating point number comparison, I was depressed.
In the N long ago, do not know where to listen to a "Do not use equal sign to compare floating point" of the "truth", their usual use, as if there is no problem, but this problem is finally come.
<?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:
Float (12300)
Float (12300)
BOOL (FALSE)
I later learned that in PHP, to compare the size 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));
Results:
Float (12300)
Float (12300)
Int (0)//0 means that two floating-point values are equal
The Bccomp function can refer to the PHP manual in particular.
I hope this article will help you with your PHP program design.