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….

Tags:

Craig

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.
qr code

Leave a Comment

Your more than welcome to enter the discussion, all comments are moderated however - so please don't leave spam, it will be canned...