php - Trying to compare a calculation on float values returns false -


this question has answer here:

why equals allways false?

<?php  $a = (0.1+0.2); print $a."\n";  // results in 0.3 if ( (double)$a == (double)0.3 ) {      echo "true"; }else{      echo "not true"; } echo php_eol; 

perl

perl -e 'if ((0.2+0.1) == 0.3) {print "true\n"; } else { print "false\n"; }' 

and in python

python -c 'if ((0.2+0.1)!=0.3 ):  print "false" ' 

you need specify tolerance [also referred epsilon] when comparing floating point values since it not exact representation of number.

function f_cmp(float $a, float $b, float $tol = 0.00001) {   if( abs($a - $b) < $tol ) { return 0; }   else { return $a - $b; }   // return 0 if "equal" within tolerance   // return < 0 if $a < $b   // return > 0 if $a > $b   // use php functions usort() } 

or simply:

function f_eq(float $a, float $b, float $tol = 0.00001) {   if( abs($a - $b) < $tol ) { return true; }   else { return false; } } 

Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -