RE: [PHP-DEV] Float comparison

From: Date: Fri, 02 May 2008 17:38:47 +0000
Subject: RE: [PHP-DEV] Float comparison
References: 1 2  Groups: php.internals 
Request: Send a blank email to internals+get-37406@lists.php.net to get a copy of this message
Thanks Pierre, I realize it's not a "bug" and I've read some "bogus" reports :) But since (float)(string)$test == (double)1960 is 'correct' My question is: can php do the conversion internally? It would seem *very* convenient for users, If not changing the float behavior, I'm advocating for a (numeric) type that does this magic conversion. (numeric) == (float)(string) in en_US locale / convert to string with a "." seperator Let's say it's hard to promote PHP as enterprise ready without dealing so well with numbers. I don't know the float-to-string internals but it seems to do 'right' thing. We get '1960', then converting back to a float, all accuracy bits are 0, so (numeric)$test == (double)1960 I would guess adding a new type is a big amount work? -----Original Message----- From: Pierre Joye [mailto:pierre.php@gmail.com] Sent: May 2, 2008 1:05 PM To: Jonathan Bond-Caron Cc: internals@lists.php.net Subject: Re: [PHP-DEV] Float comparison On Fri, May 2, 2008 at 6:52 PM, Jonathan Bond-Caron <jbondc@openmv.com> wrote: > Hi, > > > > I'm new to the PHP internals list and I'm posting an issue I'm sure has been > mentioned before -- float comparison > > > > I'd like to know if there are reasons not to change the default behavior > when comparing floats. > > > > i.e. This would seem logical to me: > > > > $test = 19.6*100; > > if((float)(string)$test == (double)1960) > > echo "GOOD BEHAVIOR"; > > > > // Implicitely convert the float to string then float (en_US > locale) > > if($test == (double)1960) > > echo "THIS SHOULD PASS by casting > (float)(string)$test internally..."; > > else > > echo "NOT GOOD BEHAVIOR"; > > > > // Exact comparison would still fail > > if($test !== (double)1960) > > echo "GOOD BEHAVIOR"; > > > > Any reason why $test == (double)1960 should fail? I realized we are > comparing two floats, but couldn't php internally convert to string then > float - for the non strict (===) case From our bug report: " Floating point values have a limited precision. Hence a value might not have the same string representation after any processing. That also includes writing a floating point value in your script and directly printing it without any mathematical operations. If you would like to know more about "floats" and what IEEE 754 is read this: http://docs.sun.com/source/806-3568/ncg_goldberg.html Thank you for your interest in PHP. " We use this text as automatic reply for bugs about floating points (aka bogus). Cheers, -- Pierre http://blog.thepimp.net | http://www.libgd.org

« previous php.internals (#37406) next »