php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #41213 Subtracting 2 floats returns incorrect results
Submitted: 2007-04-27 13:55 UTC Modified: 2007-04-27 14:42 UTC
From: jsbruns at selectionsheet dot com Assigned:
Status: Not a bug Package: Math related
PHP Version: 5.2.1 OS: Windows NT Server
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: jsbruns at selectionsheet dot com
New email:
PHP Version: OS:

 

 [2007-04-27 13:55 UTC] jsbruns at selectionsheet dot com
Description:
------------
Attempting to subtract one floating point number from another returns the incorrect result. Float 1 is assigned in the code, float 2 is retrieved from a mysql DB field, which is of type DECIMAL(5,4).

When subtracting $float1 from $float2 the result is:
-7.105427357601E-015  

Reproduce code:
---------------
//Field discount2 is defined as type DECIMAL(5.4). Original value in database is 0.56, use PHP to multiply by 100 to get a whole number (56).

$result = mysql_query("SELECT `discount2` 
FROM `product_discounts` 
WHERE `product_id` = 'prod1'"); 

$discount2 = mysql_result($result)*100; 
$discount1 = 56; 

echo $discount1; //56 
echo $discount2; //56 

if ($discount2 != $discount1)
  echo "Discount1 not equal to Discount2"; //Y
if (bccomp($discount1,$discount2) == 0)
  echo "Discount1 equal to Discount2"; //Y


echo ($discount1 + $discount2); //112 
echo ($discount1 - $discount2); //-7.105427357601E-015  


Expected result:
----------------
When subtracting $discount1 from $discount2 I expected to get 0. When adding the two I get the expected 112.

Actual result:
--------------
When subtracting $discount1 from $discount2 I get:
-7.105427357601E-015  

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2007-04-27 14:42 UTC] tony2001@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: Fri May 09 17:01:28 2025 UTC