I want to compare two floats in PHP, like in this sample code:
$a = 0.17;
$b = 1 - 0.83; //0.17
if($a == $b ){
echo \'a and b are same\';
}
else {
echo \'a
If you have floating point values to compare to equality, a simple way to avoid the risk of internal rounding strategy of the OS, language, processor or so on, is to compare the string representation of the values.
You can use any of the following to produce the desired result: https://3v4l.org/rUrEq
String Type Casting
if ( (string) $a === (string) $b) { … }
String Concatenation
if ('' . $a === '' . $b) { … }
strval function
if (strval($a) === strval($b)) { … }
String representations are much less finicky than floats when it comes to checking equality.