Bug #70447 [Opn->Nab]: Wrong float rounding using round function
| From: | requinix@php.net | Date: | Mon, 07 Sep 2015 11:23:19 +0000 |
| Subject: | Bug #70447 [Opn->Nab]: Wrong float rounding using round function | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-195840@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=70447&edit=1
ID: 70447
Updated by: requinix@php.net
Reported by: m dot mochetti at design-it dot de
Summary: Wrong float rounding using round function
-Status: Open
+Status: Not a bug
Type: Bug
Package: *General Issues
Operating System: Linux (ubuntu)
PHP Version: 5.5.29
Block user comment: N
Private report: N
New Comment:
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.
Previous Comments:
------------------------------------------------------------------------
[2015-09-07 11:14:25] 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
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=70447&edit=1