php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #32488 printf: %d not equal %s for some numbers
Submitted: 2005-03-29 19:23 UTC Modified: 2005-03-30 03:16 UTC
From: glowack2 at msu dot edu Assigned:
Status: Not a bug Package: *General Issues
PHP Version: 5.0.3 OS: Linux
Private report: No CVE-ID: None
 [2005-03-29 19:23 UTC] glowack2 at msu dot edu
Description:
------------
printf (and sprintf) output incorrect values for certain inputs when using the %d placeholder.  For example, printf("%d",10.20*100) outputs "1019", which is clearly not the correct and expected value of "1020".  Most of the time, the printed value is correct, but various numbers are off by one.  The off-by-one error is tied to specific numbers, and it is repeatable.  The off-by-one error also occurs when decimals are multiplied by other powers of 10 (10, 100, 1000), though the numbers that produce errors are not consistent between the different powers

This originally occured on a Solaris 5.6 machine running PHP 4.x, and has been reproduced on a Linux machine running PHP 5.0.3.

The sample code included generates a table that verifies the output of %d against %s (%s works correctly), green cells for matching output and red cells with more details when the resulting text doesn't match.

Reproduce code:
---------------
print "<table>";
for($x=0;$x<1000;$x++) {
    print "<tr>";
    for($y=0.1;$y<1;$y=$y+0.1) {
        // For more errors, replace *100 with *10 or *1000
        // in the following two lines:
        $string = sprintf("%s",($x+$y)*100);
        $decimal = sprintf("%d",($x+$y)*100);
        if(strcmp($string,$decimal)==0) {
            print "<td bgcolor='#ddffdd'>$string</td>";   
        } else {
            print "<td bgcolor='#ffdddd'>$string != $decimal</td>";   
        }
        
    }
    print "</tr>";
}

Expected result:
----------------
Every cell *should* be green, because sprintf should always convert numbers accurately.

Actual result:
--------------
%d and %s output different results for certain decimal numbers.  Only some values come out incorrectly, and most are fine.

Patches

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2005-03-30 03:16 UTC] alan_k@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://docs.sun.com/source/806-3568/ncg_goldberg.html
 
Thank you for your interest in PHP.

.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Fri Aug 16 04:01:28 2024 UTC