Here is a Perl script:
#!/usr/bin/perl
use strict;
use warnings;
use feature 'say';
my @numbers = qw(
0.254
0.255
0.256
);
foreach my $number (@numbers) {
my $rounded = sprintf '%.2f', $number;
say "$number => $rounded";
}
foreach my $number (@numbers) {
$number += 100;
my $rounded = sprintf '%.2f', $number;
say "$number => $rounded";
}
It outputs:
0.254 => 0.25
0.255 => 0.26
0.256 => 0.26
100.254 => 100.25
100.255 => 100.25
100.256 => 100.26
For me it is very strange that Perl is inconsistent with rounding. I expect that both number ending with .255 to be rounded as .26 It is true for 0.255, but it is false for the number 100.255.
Here is the quote from Perl Cookbook, http://docstore.mik.ua/orelly/perl/cookbook/ch02_04.htm,
sprintf . The f format lets you specify a particular number of decimal places to round its argument to. Perl looks at the following digit, rounds up if it is 5 or greater, and rounds down otherwise.
But I can't see any evidence that it is correct in http://perldoc.perl.org/functions/sprintf.html
Is it a bug in sprintf or Perl Cookbook is wrong? If it is desired behaviour, why does it work this way?