note 63619 added to language.types.float
| From: | david at davidmosesNO dot SPAM dot ca | Date: | Sat, 25 Mar 2006 21:48:23 +0000 |
| Subject: | note 63619 added to language.types.float | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-106611@lists.php.net to get a copy of this message | ||
Re: rick at ninjafoo dot com
There is no need to âalwaysâ use the BCMath functions. We just need to heed the
documentation and ânever compare floating point numbers for equalityâ.
The reason (19.6*100) !== (double)1960, is because inside a computer they are not equal.
Try this:
<?php
printf("%.15f", (19.6*100));
?>
Outputs: 1960.000000000000227 (not 1960 as somewhat expected)
If comparison is required a few options come to mind (other than BCMath):
1) Round numbers before comparison:
<?php
$sig_figs = 5;
echo (round((19.6*100), $sig_figs) !== round((double)1960, $sig_figs)) ? 'not equal' :
'equal';
?>
Outputs: equal
2) Another method is to use a tolerance value, and consider numbers equal if their difference is
less than the tolerance.
----
Server IP: 66.163.161.117
Probable Submitter: 69.195.8.22
----
X-Spam-Status: No, hits=3.1 required=5.0 tests=DATE_MISSING,FROM_NO_LOWER
autolearn=no version=2.64
----
Manual Page -- http://www.php.net/manual/en/language.types.float.php
Edit -- http://master.php.net/note/edit/63619
Del: integrated -- http://master.php.net/note/delete/63619/integrated
Del: useless -- http://master.php.net/note/delete/63619/useless
Del: bad code -- http://master.php.net/note/delete/63619/bad+code
Del: spam -- http://master.php.net/note/delete/63619/spam
Del: non-english -- http://master.php.net/note/delete/63619/non-english
Del: in docs -- http://master.php.net/note/delete/63619/in+docs
Del: other reasons-- http://master.php.net/note/delete/63619
Reject -- http://master.php.net/note/reject/63619
Search -- http://master.php.net/manage/user-notes.php