note 44595 added to function.floor
| From: | jolyon at mways dot co dot uk | Date: | Tue, 10 Aug 2004 16:41:48 +0000 |
| Subject: | note 44595 added to function.floor | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-74409@lists.php.net to get a copy of this message | ||
Beware of FLOAT weirdness!
Floats have a mind of their own, and what may look like an integer stored in a float isn't.
Here's a baffling example of how floor can be tripped up by this:
<?
$price = 79.99;
print $price."\r\n"; // correct result, 79.99 shown
$price = $price * 100;
print $price."\r\n"; // correct result, 7999 shown
print floor($price); // 7998 shown! what's going on?
?>
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 79.99 was multiplied by 100, the actual value stored in the float was
probably something like 7998.9999999999999999999999999999999999, PHP would print out 7999 when the
value is displayed but floor would therefore round this down to 7998.
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 :)
----
Manual Page -- http://www.php.net/manual/en/function.floor.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+44595
Delete -- http://master.php.net/manage/user-notes.php?action=delete+44595&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+44595&report=yes
Search -- http://master.php.net/manage/user-notes.php