NYCPHP Meetup

NYPHP.org

[nycphp-talk] Unfriendly Float Handling

Bill Patterson patterson at computer.org
Sun Apr 2 19:44:27 EDT 2006


This has been a problem in the computer field for decades.  Many 
language developers have not understood the importance of precision in 
this way.  I agree that it would be good to have a type of number that 
is treated as fixed.

In C++ this can be addressed by operator overloading.  But PHP doesn't 
have operator overloading so it would have to be done with more 
non-visually pleasing object methods without a change to the language.

Bill

Tim McEwen wrote:

>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
>_______________________________________________
>New York PHP Community Talk Mailing List
>http://lists.nyphp.org/mailman/listinfo/talk
>New York PHP Conference and Expo 2006
>http://www.nyphpcon.com
>Show Your Participation in New York PHP
>http://www.nyphp.org/show_participation.php
>
>
>  
>




More information about the talk mailing list