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
onion2k
Jedi Mod
Posts: 5263 Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com
Post
by onion2k » Tue Apr 15, 2008 5:25 am
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.
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098 Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia
Post
by Chris Corbyn » Tue Apr 15, 2008 5:28 am
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.
onion2k
Jedi Mod
Posts: 5263 Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com
Post
by onion2k » Tue Apr 15, 2008 5:34 am
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.
Ambush Commander
DevNet Master
Posts: 3698 Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US
Post
by Ambush Commander » Tue Apr 15, 2008 10:16 pm
Two words: arbitrary precision.
Creating a money object works too....