php.net |  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
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:
MUST BE VALID
Solve the problem:
34 + 35 = ?
Subscribe to this entry?

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

Reproduce code:
---------------
<?php
echo "<pre>";
$total = 332.145;
$substract = 274.5;
$myVal = $total-$substract;
var_dump($myVal);
var_dump(round(57.645,2));
var_dump(round($myVal,2));
var_dump(round("$myVal",2));
echo "</pre>";
?>

Expected result:
----------------
float(57.645)
float(57.65)
float(57.65)
float(57.65)


Actual result:
--------------
float(57.645)
float(57.65)
float(57.64)
float(57.65)


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2008-09-02 09:28 UTC] scottmac@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.


 [2008-09-02 09:32 UTC] mattwil@php.net
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: Wed Aug 17 16:05:45 2022 UTC