When I do a very simple floor(200*1.14) I get the result 227 instead of 228. How does PHP manage to screw this up and how can I make it not do that? I'm using PHP 5.2.13.
Thats due to the fact that you're flooring the value. Which does not round it. Use the round function instead: round ( float $val [, int $precision = 0 [, int $mode = PHP_ROUND_HALF_UP ]] )
<?php if(is_int(200*1.14)) /* if the number is integer dont floor it else floor it */ echo 200*1.14 ; else echo floor(200*1.14); ?> Code (markup):
I don't really get this. 200*1.14 does equal 228 exactly so why should flooring it give 227. I always thought flooring rounded down to the nearest whole integer although I'm doubting that given AdsMakesSense's comments. Does that mean that even if the current value IS an integer, it'll ignore that and take the next lower integer value? Seems like very odd functionality. Maybe it's just too early in the morning to be thinking about PHP and I'm missing something!
The thing to remember here is that the way a float stores a value makes it very easy for these kind of things to happen. When the 1.14 was multiplied by 200, the actual value stored in the float was probably something like 227.9999999999999999999999999999999999, PHP would print out 228 when the value is displayed but floor would therefore round this down to 227. The moral of this story - never use float for anything that needs to be accurate! If you're doing prices for products or a shopping cart, then always use an integer and store prices as a number of pence, you'll thank me for this later
So the only solution is, <?php if(is_int(200*1.14)) /* if the number is integer dont floor it else floor it */ echo 200*1.14 ; else echo floor(200*1.14); ?>