NYCPHP Meetup

NYPHP.org

[nycphp-talk] Unfriendly Float Handling

Tim McEwen tim at tmcode.com
Fri Mar 31 16:58:49 EST 2006


I apologize if this has already been discussed to death here but I  
would love to hear people's thoughts on it.    I am trying to justify  
to a colleague why the behavior below is not a massive flaw in PHP.    
To a new programmer,   the following code should result in  $a being  
equal to $b:

$a="49.95" + "3.95";   // or even  $a = 49.95 + 3.95;
$b=53.90;

Unfortunately floats in PHP are subject to the same problems you find  
in many languages with fixed precision.   So due to rounding, in this  
case $a is not equal to $b.     This behavior is documented in the  
manual:  http://www.php.net/manual/en/ 
language.types.float.php#AEN3375    Straight from the manual:  "So  
never trust floating number results to the last digit and never  
compare floating point numbers for equality."   Come again?  Never  
compare floating point numbers for equality?   And thats not a bad  
thing?

Given the fact that PHP is so easy to learn and that it is very  
commonly used for financial related tasks such as ecommerce,  doesn't  
it stand to reason that people will assume that they can use the  
internal PHP operators on dollar amounts?   Since many people are  
going to just assume they can do math in a natural manner,  shouldn't  
PHP a little more proactive to ensure that developers won't get  
burned by this?

I've spoken to a few php contributors about this have had very little  
interest in tackling this issue.  The "official" answer is that if  
you are doing math on fixed precision numbers you should use either  
the bc or gmp but these extension as not even enabled by default.

 From what I understand,  there would be a speed penalty for  
detecting and dealing with fixed percision numbers.  Some people  
might not mind the speed hit so why not make it a configurable  
choice?  Or why not create a built in fixed precision type?  Whatever  
the case, I think PHP needs a built in solution that does not rely on  
extensions. Thoughts?

-Tim



More information about the talk mailing list