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
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.
Password:
Status:
Package:
Bug Type:
Summary:
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
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-2024 The PHP Group
All rights reserved.
Last updated: Thu Apr 18 17:01:28 2024 UTC