in reply to Re: Rounding a number?
in thread Rounding a number?
My first thought when I saw this question was sprintf, which is Perl's standard approach to rounding, but then I saw ghenry's comment and realized that sprintf doesn't do what the OP specifically asked for, because for numbers exactly at the halfway point between two integers, perl always rounds towards the even number.
Due to the "miracles" of IEEE floating point computation and rounding, we also have the following craziness:
$ perl -e'for( $d=0; $d<1; $d+=0.05 ){ printf "%.2f ~ %.1f\n", $d, $d; + }' 0.00 ~ 0.0 0.05 ~ 0.1 0.10 ~ 0.1 0.15 ~ 0.2 0.20 ~ 0.2 0.25 ~ 0.2 0.30 ~ 0.3 0.35 ~ 0.3 0.40 ~ 0.4 0.45 ~ 0.4 0.50 ~ 0.5 0.55 ~ 0.5 0.60 ~ 0.6 0.65 ~ 0.7 0.70 ~ 0.7 0.75 ~ 0.8 0.80 ~ 0.8 0.85 ~ 0.9 0.90 ~ 0.9 0.95 ~ 1.0
(Notice the 3 0.2s and only 1 0.6. At least the output from an equivalent C program is identical.) But this should be expected with floating point ...
|
|---|