php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #33731 Rounding error when casting
Submitted: 2005-07-17 07:36 UTC Modified: 2005-07-17 18:17 UTC
Votes:1
Avg. Score:3.0 ± 0.0
Reproduced:1 of 1 (100.0%)
Same Version:1 (100.0%)
Same OS:1 (100.0%)
From: peebrain at psipog dot net Assigned:
Status: Not a bug Package: Math related
PHP Version: 4.3.11 OS: Linux
Private report: No CVE-ID: None
 [2005-07-17 07:36 UTC] peebrain at psipog dot net
Description:
------------
When rounding with int casting, it seems to screw it up on this weird case.  If you cast 230 to int, it will change to 229 in this one case.

Reproduce code:
---------------
$r = 2.3;
echo $r."<BR>";
$r = $r * 100.0;
echo $r."<BR>";
$r = (int)$r;
echo $r."<BR>";
$r = $r / 100.0;
echo $r;

Expected result:
----------------
2.3
230
230
2.3

Actual result:
--------------
2.3
230
229
2.29 

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2005-07-17 07:48 UTC] rasmus@php.net
This is not a bug.  Computers have no way to represent floating point numbers accurately.  They can only approximate them to a certain precision.  Whenever you do anything that requires absolute precision, you need to take this into account.  2.3*100 is never going to be exactly 230.  It's going to be 229.99999999999999999 or 230.0000000000000001 and if you do (int)229.99999999999999999 you are going to get 229.
 [2005-07-17 17:59 UTC] peebrain at psipog dot net
Shouldn't the third echo produce 229.999999999 then, instead of 230?
 [2005-07-17 18:00 UTC] peebrain at psipog dot net
Sorry, I mean... shouldn't the SECOND echo produce 229.9999999 ?
 [2005-07-17 18:17 UTC] rasmus@php.net
No, because the is a precision adjustment for display purposes.  That's what the precision .ini setting is all about.  Also note that when you multiply a floating point value you are magnifying this floating point error inherent in all floating point operations.
 
PHP Copyright © 2001-2020 The PHP Group
All rights reserved.
Last updated: Sun Nov 29 05:01:23 2020 UTC