php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #54094 Sprintf change integer with %d
Submitted: 2011-02-24 18:06 UTC Modified: 2011-02-24 18:16 UTC
Votes:1
Avg. Score:5.0 ± 0.0
Reproduced:0 of 0 (0.0%)
From: mallsbill at gmail dot com Assigned:
Status: Not a bug Package: Strings related
PHP Version: 5.2.17 OS: Linux debian 2.6.26-2-686
Private report: No CVE-ID: None
View Add Comment Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: mallsbill at gmail dot com
New email:
PHP Version: OS:

 

 [2011-02-24 18:06 UTC] 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);

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2011-02-24 18:16 UTC] rasmus@php.net
-Status: Open +Status: Bogus
 [2011-02-24 18:16 UTC] rasmus@php.net
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.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Mar 28 10:01:26 2024 UTC