|  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #45970 Weird rounding behaviour
Submitted: 2008-09-02 09:08 UTC Modified: 2008-09-02 09:32 UTC
From: jan dot vernieuwe at webline dot be Assigned:
Status: Not a bug Package: Math related
PHP Version: 5.2.6 OS: FreeBSD
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 this is not your bug, you can add a comment by following this link.
If this is your bug, but you forgot your password, you can retrieve your password here.
Bug Type:
From: jan dot vernieuwe at webline dot be
New email:
PHP Version: OS:


 [2008-09-02 09:08 UTC] jan dot vernieuwe at webline dot be
Rounding a calculated float gives bad results, rounding it as a string works as intended.

Reproduce code:
echo "<pre>";
$total = 332.145;
$substract = 274.5;
$myVal = $total-$substract;
echo "</pre>";

Expected result:

Actual result:


Add a Patch

Pull Requests

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [2008-09-02 09:28 UTC]
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:
Thank you for your interest in PHP.

 [2008-09-02 09:32 UTC]
Oh, Scott just beat me. :-) Well here's a bit extra I wrote:

The result of subtraction ($myVal) is stored as a value slightly less than 57.645, due to floating-point precision, which is why it rounds to 57.64 in the 3rd var_dump(). The 2nd and 4th var_dump() are using the same value, with closer float representation to what you want (57.645). By that I mean, in the 4th, as a string, $myVal is first converted to a string, exactly as the first example does to print the var_dump() output, then that "57.645" string is converted to float, exactly as the numeric version in the 2nd example is when the script is parsed/compiled (so they have the same internal float representation, and will behave the same).
PHP Copyright © 2001-2022 The PHP Group
All rights reserved.
Last updated: Tue Aug 09 20:05:45 2022 UTC