|   | php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login | 
| 
 PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits              [2005-03-30 03:16 UTC] alan_k@php.net
 | |||||||||||||||||||||||||||
|  Copyright © 2001-2025 The PHP Group All rights reserved. | Last updated: Fri Oct 31 04:00:01 2025 UTC | 
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.