Page 1 of 1

Very odd float problem.

Posted: Tue Apr 15, 2008 5:25 am
by onion2k

Code: Select all

$p = 69.99 * 100;
echo $p; // echos 6999
echo intval($p); // echos 6998
 
I've tried this on three separate PHP 4 installs and two PHP 5 machines on both Windows and Linux ... they all get it wrong. WTF?

EDIT: Ah.. http://www.phpdig.net/ref/rn65re1357.html .. it's just PHP being rubbish.

Re: Very odd float problem.

Posted: Tue Apr 15, 2008 5:28 am
by Chris Corbyn
It's a floating point number. Processors can't handle floating point numbers accurately ;)

EDIT | Sorry, I didn't read your code as I should. Missed the fact your were comparing intval() with a plain echo.

Re: Very odd float problem.

Posted: Tue Apr 15, 2008 5:34 am
by onion2k
floor() has the same problem.

Fortunately if you do..

Code: Select all

$p = strval(69.99*100);
echo intval($p);
 
.. it works just fine.

PHP, the language that encourages really nasty hacks. :banghead:

Re: Very odd float problem.

Posted: Tue Apr 15, 2008 10:16 pm
by Ambush Commander
Two words: arbitrary precision.

Creating a money object works too....

Re: Very odd float problem.

Posted: Wed Apr 16, 2008 4:01 am
by dbevfat
We're using Quantity (Money) object (see http://martinfowler.com/ap2/quantity.html), with bcmath (http://si.php.net/manual/en/ref.bc.php) functions for precise calculations. Floats just won't do it. :)