Categories
Dev

PHP floating point precision

I was attempting to find if the result of a calculation returned a number with any decimals.

So, I was doing something like:

$num=123.1/0.1;
if(floor($num)!=$num){
  echo "has decimals";
}else{
  echo "doesn't have decimals";
}
//has decimals

To my surprise the code above returns: ‘has decimals’

If you do the math in any calculator the result of 123.1/0.1=1231 and in fact that is what PHP displays when you do:

echo 123.1/0.1;
//1231

But internally PHP stores the value in float and when you do:

echo floor(123.1/0.1);
//1230

As I only need to know if the number has any decimals, I ended up doing:

$num=round(123.1/0.1,1);
if(floor($num)!=$num){
  echo "has decimals";
}else{
  echo "doesn't have decimals";
}

I completely understand why Steve Wozniak never got round to add floating point support on BASIC, no sane person wants to deal with floating points.