php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #70447 Wrong float rounding using round function
Submitted: 2015-09-07 11:14 UTC Modified: 2015-09-07 11:45 UTC
From: m dot mochetti at design-it dot de Assigned:
Status: Not a bug Package: *General Issues
PHP Version: 5.5.29 OS: Linux (ubuntu)
Private report: No CVE-ID: None
 [2015-09-07 11:14 UTC] m dot mochetti at design-it dot de
Description:
------------
I'm having a serious issue regarding prices not being properly rounded in a sales platform the company I work for is currently developing.


Please take a look at the Test script attached, it showcases the issue.

Test script:
---------------
<?php

$float = 87.755;
$units = (int)floor($float);
$cents = (float)($float - $units);

echo "UNITS = ".$units; // UNITS = 87
echo "<br>";

echo "CENTS = ".$cents; // CENTS = 0.755
echo "<br>";

echo "ROUNDED CENTS = ".round($cents, 2); // ROUNDED CENTS = 0.75 --> WRONG!!
echo "<br>";

echo "ROUNDED CENTS (without using variable): ".round(0.755, 2); // ROUNDED CENTS (without var) : 0.76 --> CORRECT!!

?>

Expected result:
----------------
round(0.755, 2) should return the same result as round($var, 2) // being $var a calculated value that ended up to be 0.755

Actual result:
--------------
round(0.755,2) = 0.76

round($var, 2) = 0.75

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2015-09-07 11:23 UTC] requinix@php.net
-Status: Open +Status: Not a bug
 [2015-09-07 11:23 UTC] requinix@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://www.floating-point-gui.de/

Thank you for your interest in PHP.

<?php
ini_set("precision", 20);
$float = 87.755;
$units = (int)floor($float);
$cents = (float)($float - $units);
var_dump($cents);
?>
float(0.75499999999999545253)

(that was with PHP x86 on Windows)

Round to three decimal places first, as that is the value you expected to be working with. Then round it to two decimal places.
 [2015-09-07 11:45 UTC] m dot mochetti at design-it dot de
Ok, so added the following line of code:
$cents = round(round($cents,3), 2);

And works fine.

Thanks.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Sun May 19 14:01:32 2024 UTC