#35896 [Opn->Bgs]: Round() not doing what it says on the tin
| From: | sniper@php.net | Date: | Wed, 04 Jan 2006 19:39:20 +0000 |
| Subject: | #35896 [Opn->Bgs]: Round() not doing what it says on the tin | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-91481@lists.php.net to get a copy of this message | ||
ID: 35896
Updated by: sniper@php.net
Reported By: matt at equaliser dot net
-Status: Open
+Status: Bogus
Bug Type: Math related
Operating System: Linux
PHP Version: 4.4.1
New Comment:
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.
Previous Comments:
------------------------------------------------------------------------
[2006-01-04 20:37:21] matt at equaliser dot net
Soory - I got the expected result and the actual result interposed in
my previous posting.
------------------------------------------------------------------------
[2006-01-04 20:30:50] matt at equaliser dot net
Description:
------------
I know *why* this is happening - so please don't point me to
http://www.php.net/manual/en/language.types.float.php
- I'm aware of
this.
This does not change the fact that a pure call to the round() function
using a float value stored in memory can return the wrong result.
The fact that this is easily fixed by rounding to one decimal place
further along the float before performing the actual rounding, simply
makes the continued existence of this bug more baffling. Why doesn't
PHP round() do this internally?
Do all PHP developers need to roll their own round() function if they
are going to guarantee mathematical accuracy?
Reproduce code:
---------------
<?php
$input_value = 45;
$vat = $input_value * .175;
echo $vat . '<br />';
echo round($vat , 2) . '<br />';
echo round(strval($vat) , 2) . '<br />';
echo round(round($vat , 3) , 2) . '<br />';
$input_value2 = 7.875;
echo round($input_value2 , 2) . '<br />';
echo round(7.875 , 2) . '<br />';
echo $vat - $input_value2;
?>
Expected result:
----------------
7.875
7.87
7.88
7.88
7.88
7.88
-8.8817841970013E-16
Actual result:
--------------
7.875
7.88
7.88
7.88
7.88
7.88
-8.8817841970013E-16
------------------------------------------------------------------------
--
Edit this bug report at http://bugs.php.net/?id=35896&edit=1