Very odd float problem.

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

Post Reply
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Very odd float problem.

Post 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.
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Re: Very odd float problem.

Post 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.
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Re: Very odd float problem.

Post 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:
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Re: Very odd float problem.

Post by Ambush Commander »

Two words: arbitrary precision.

Creating a money object works too....
User avatar
dbevfat
Forum Contributor
Posts: 126
Joined: Tue Jun 28, 2005 2:47 pm
Location: Ljubljana, Slovenia

Re: Very odd float problem.

Post 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. :)
Post Reply