The Developer Day | Staying Curious

Apr/08

7

Lost PHP float precision

I was preparing for the Zend certificate exam and while reading the first pages of the Zend study guide I found some interesting things. Here’s a simple snippet of PHP code:

echo (int) ( (0.1+0.7) * 10 );

What do you think the output would be? Surprisingly it’s 7. Internally in PHP it’s stored as 7.999999. Gladly this problem is described in PHP manual about float precision.

And sadly .. How many developers starting to develop PHP applications read about integers and float? When I started with PHP I thought to myself.. Hey it’s there. It’s simple and it works. What could be wrong with it? And after a while you wake up developing so called “enterprise applications” and you might start banging your head to the wall when you find out your reports are not so accurate as you thought :) Probably not many developers make their priority to read about integers and floats?

Turns out this is a usual thing. A quote from PHP.net manual:

"It is quite usual that simple decimal fractions like 0.1 or 0.7 cannot be converted into their internal binary counterparts without a little loss of precision."

PHP.net manual suggests developers should use bcmath extension if higher precision is needed. Not only you can not cast floats to integers but you have to be careful comparing floats.

You might never run into this problem. But when you do it may come as an unpleasant surprise trying to find where is that single penny lost..

RSS Feed

3 Comments for Lost PHP float precision

Prity Ladsaria Roy | April 7, 2008 at 3:21 PM

Thank you for wonderful word of advice.

I have been developing in PHP and also I am the technical lead at my organization and there are times I have to give lot of training to the new recruits.

I think this piece of advice will be very useful and will also be included in my trainings.

But it is surprising how we miss so many these details in our codes.

Thank you once again.

philip | March 10, 2009 at 11:49 PM

Very good advice for beginning developers!

Really, you have found a very common problem.
((int) ( (0.1+0.7) * 10 )==7) it’s NOT PHP PROBLEM, it’s float data type problem. IEE standard problem, to say more.

Java, c++, any language suffer exactly same way.
And beginning developers suffer too.
On http://www.ibm.com/developerworks/ru/library/j-jtp0114/index.html you can read good introduction, with useful links on the bottom of page.

Blake | December 31, 2010 at 3:59 PM

Good point, Phillip — other languages suffer the same issue, and the problem is the precision of floating-point numbers, not PHP. However, PHP suffers more than other languages because it lacks an integer division operator. For example, when you divide two ints in Java, the result is an int. In PHP, the result is a float. In VB, for example, I believe there is a special integer division operator; this is what PHP could use.

Leave a comment!

<<

>>

Find it!

Theme Design by devolux.org