How to category Design category Development category News category

how not to round your floats…

Just so I never foget… observe the following test cases –

$foo = 8.37*40*0.175*100; echo $foo.' == '.(int)$foo;
> 5859 == 5858

$foo = 8.37*40*0.175*100; echo $foo.' == '.round($foo);
> 5859 == 5859

I believe that casing to INT will round towards zero as documented in the php docs, I also believe the 5858 number above is because the floating point number is always fractional…

another interesting one –

$foo = 8.37*40*0.175*100; echo $foo.' == '.(int)(string)$foo;
> 5859 == 5859

By casting to string first the floating point element is removed….



Craig enjoys producing usable and friendly sites that look great and function well. He often also experiments with workflow automation and owns and runs web-engineer.

Comments are closed.