Compare floats in php

后端 未结 16 1671
清歌不尽
清歌不尽 2020-11-22 00:47

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         


        
16条回答
  •  后悔当初
    2020-11-22 01:32

    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.

提交回复
热议问题