I've come across what I feel is inconsistent rounding with PHP's sprintf()
function. The following code:
$n = 691.625;
$s = sprintf("%.2f", $n);
$r = round($n, 2);
print "$n: $s $r\n";
$n = 17.565;
$s = sprintf("%.2f", $n);
$r = round($n, 2);
print "$n: $s $r\n";
$n = 19.875;
$s = sprintf("%.2f", $n);
$r = round($n, 2);
print "$n: $s $r\n";
produces the following output:
691.625: 691.62 691.63
17.565: 17.57 17.57
19.875: 19.88 19.88
I expected the following:
691.625: 691.63 691.63
17.565: 17.57 17.57
19.875: 19.88 19.88
The difference is in the second number on the first line. So my question is, why does sprintf()
round down for the first number and up for the second and third?
I've replicated this under PHP 5.4, 5.5 and 7.0. I've included a comparison with the result of round()
.
(I thought it might have been the internal floating point representation, but all three appear to be stored correctly.)