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
Anyone can comment on a bug. Have a simpler test case? Does it work for you on a different platform? Let us know!
Just going to say 'Me too!'? Don't clutter the database with that please !
Your email address:
MUST BE VALID
Solve the problem:
18 - 11 = ?
Subscribe to this entry?

 
 [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 18:01:29 2024 UTC