Bug #54094 [Opn->Bgs]: Sprintf change integer with %d
| From: | rasmus@php.net | Date: | Thu, 24 Feb 2011 17:16:15 +0000 |
| Subject: | Bug #54094 [Opn->Bgs]: Sprintf change integer with %d | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-159020@lists.php.net to get a copy of this message | ||
Edit report at http://bugs.php.net/bug.php?id=54094&edit=1
ID: 54094
Updated by: rasmus@php.net
Reported by: mallsbill at gmail dot com
Summary: Sprintf change integer with %d
-Status: Open
+Status: Bogus
Type: Bug
Package: Strings related
Operating System: Linux debian 2.6.26-2-686
PHP Version: 5.2.17
Block user comment: N
Private report: N
New Comment:
Floating point math is not exact. 4.77 * 100 cannot be accurately
represented so
it ends up being 476.9999999999999999 and when you cast that to an
integer the way
you are doing you get 476. You can read more about it here:
http://en.wikipedia.org/wiki/IEEE_754-2008
In your case add a round() to the appropriate precision on your floating
point
operation.
Previous Comments:
------------------------------------------------------------------------
[2011-02-24 18:06:37] mallsbill at gmail dot com
Description:
------------
---
From manual page: http://www.php.net/function.sprintf#Description
---
with some integer obtain after an operation from a float, sprintf('%d',
$val) return a different value
Test script:
---------------
$var1 = 4.77*100;
echo $var2 = sprintf("%d", $var1);
Expected result:
----------------
should return 477
Actual result:
--------------
return 476
works when cast in string
$var1 = 4.77*100;
echo $var2 = sprintf("%d", (string)$var1);
------------------------------------------------------------------------
--
Edit this bug report at http://bugs.php.net/bug.php?id=54094&edit=1