Casteele/ShadowLord wrote: > > Actually, Bill's answer has an error.. Adding .05 just introduces a subtle > error because some > decimal floating point numbers cannot be exactly represented in binary form. > For example: > > my ($i, $j); > foreach $i (0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5) { > $j = $i + .05; > printf "%.20f\t%.20f\t%.1f\n", $i, $j, $j; > }
That can be resolved by using a smaller value than .05. Actually, I use something like this to do my rounding when CPU isn't important : sub round ($;$) { # $ret = round ($num, [$digits:2]) my ($num, $dp) = (@_, 2); # default decimal places is 2 int ($num * 10 ** $dp + ($num < 0 ? -.5 : .5)) / 10 ** $dp; } so it would be : foreach my $ii (0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5) { printf "%.0f\n", round ($ii); } Yielding: 0.5 1.5 2.5 3.5 4.5 5.5 6.5 7.5 8.5 9.5 > I think what Bill really meant to do.. To round a whole number (an integer), > use something > like this: > > my ($i, $j); > foreach $i (0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5) { > $j = int($i + .5); > printf "%.20f\t%.20f\t%.0f\n", $i, $j, $j; > } No, that's not what I intended to do. You can still use (s)printf alone to do the job - just use something smaller than 1/2 of the next place (like .01) or use a routine like the one above for something more robust. I never use int in the process - but that's just me. _______________________________________________ Perl-Win32-Users mailing list Perl-Win32-Users@listserv.ActiveState.com To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs