#33731 [Bgs]: Rounding error when casting

From: Date: Sun, 17 Jul 2005 15:59:32 +0000
Subject: #33731 [Bgs]: Rounding error when casting
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-81971@lists.php.net to get a copy of this message
ID: 33731 User updated by: peebrain at psipog dot net Reported By: peebrain at psipog dot net Status: Bogus Bug Type: Math related Operating System: Linux PHP Version: 4.3.11 New Comment: Shouldn't the third echo produce 229.999999999 then, instead of 230? Previous Comments: ------------------------------------------------------------------------ [2005-07-17 07:48:58] 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 07:36:10] 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 ------------------------------------------------------------------------ -- Edit this bug report at http://bugs.php.net/?id=33731&edit=1

« previous php.bugs (#81971) next »