Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:
which works really nice... until we found out following strange behaviour:sub round($$) { sprintf "%.$_[1]f",$_[0]; } print round(8.7385, 2); # prints 8.74
...hm, the decimal part should allways be the same!for my $i (0 .. 10) { print round($i+0.555,2)," "; } # which prints: # 0.56 1.56 2.56 3.56 4.55 5.55 6.55 7.55 8.55 9.55 10.56
So here goes my first question:for (my $i = 1; $i < \xFFFF; $i <<= 1) { print round($i+0.555,2), " "; } # which prints: #1.56 2.56 4.55 8.55 16.56 32.56 64.56 128.56 256.56 512.55 #1024.56 2048.55 4096.56 8192.56 16384.56 32768.56 65536.55 #131072.55 262144.55 524288.56 1048576.55 2097152.56 4194304.55 #8388608.55 16777216.56 # #(You can try with different numbers and different precision as long # as the last digit is '5' and the precision = number of digits - 1)
...but it's somewhat obfuscated (and it does not take care of numbers like 1.5E-4).sub round2($$) { my $var=$_[0]; my $decimal=($var-int(var)); if ($decimal && ((length($decimal)-2)>$_[1]) && ($var=~/5$/)) { $var=~s/5$/6/; } sprintf "%.$_[1]f",$var; } # some output: for (my $i = 1; $i < \xFFFF; $i <<= 1) { print round($i+0.555,2), " ", round2($i+0.555,2), "\n"; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: strange rounding behaviour
by stephen (Priest) on May 18, 2001 at 20:00 UTC | |
by riffraff (Pilgrim) on May 18, 2001 at 20:35 UTC | |
by srawls (Friar) on May 19, 2001 at 00:03 UTC | |
by riffraff (Pilgrim) on May 19, 2001 at 00:26 UTC | |
|
Re: strange rounding behaviour
by lhoward (Vicar) on May 18, 2001 at 19:38 UTC | |
by tilly (Archbishop) on May 18, 2001 at 20:09 UTC | |
by lhoward (Vicar) on May 18, 2001 at 20:35 UTC |