|  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
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
View Add Comment Developer Edit
Anyone can comment on a bug. Have a simpler test case? Does it work for you on a different platform? Let us know!
Just going to say 'Me too!'? Don't clutter the database with that please !
Your email address:
Solve the problem:
46 - 22 = ?
Subscribe to this entry?

 [2005-07-17 07:36 UTC] peebrain at psipog dot net
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:

Actual result:


Add a Patch

Pull Requests

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [2005-07-17 07:48 UTC]
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]
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-2024 The PHP Group
All rights reserved.
Last updated: Wed Apr 17 01:01:29 2024 UTC