php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #42628 WRONG ARITMETHIC RESULT
Submitted: 2007-09-11 19:44 UTC Modified: 2007-09-11 20:49 UTC
From: jortac2002 at yahoo dot com dot mx Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: 5.2.4 OS: WINDOWS XP PROFESSIONAL
Private report: No CVE-ID: None
 [2007-09-11 19:44 UTC] jortac2002 at yahoo dot com dot mx
Description:
------------
I have the following code :
It is very simple code, and the result is very stange because
amounts are the same but result shows "NOT EQUAL"

Reproduce code:
---------------
<html>
<body>
<?
   $one = 1519.36;
   $two = 1153.14;
   $tree = 366.22;
   $four = $two + $tree;
   $difer = $one - $four;
   echo "one " . $one . " equals four " . $four . "<br>";
   if ($four == $one) {
      echo "THEY ARE EQUAL <br>";
   }
   else {
      echo "THEY ARE NOT  EQUAL DIFFERENCE " . $difer . "<br>";
   }
?>
</body>
</html>

Expected result:
----------------
THEY ARE EQUAL

Actual result:
--------------
THEY ARE NOT EQUAL DIFFERENCE -2.737367544323E-013

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2007-09-11 20:36 UTC] admin at ifyouwantblood dot de
This is the thing with floating numbers, just as the manual states:

   It is quite usual that simple decimal fractions like 0.1 or 0.7 cannot be converted into their internal binary counterparts without a little loss of precision.

The follwing works as you would expect it therefore:

<?

   $tree = 366.22;

   $one = 1519.36;
   $two = $one - $tree;

   $four = $two + $tree;
   $difer = $one - $four;
   echo "one " . $one . " equals four " . $four . "<br>";
   if ($four == $one) {
      echo "THEY ARE EQUAL <br>";
   }
   else {
      echo "THEY ARE NOT  EQUAL DIFFERENCE " . $difer . "<br>";
   }
?>
 [2007-09-11 20:49 UTC] pajoye@php.net
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.


 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Wed Jul 16 16:01:34 2025 UTC