On Fri, 16 Mar 2007, Su, Yu (Eugene) wrote: > Interesting. Any explanation why sprintf treats 3.5 and 4.5 > differently in rounding?
It is called "unbiased rounding", which has the advantage of not adding an upward trend to your numbers: http://en.wikipedia.org/wiki/Rounding Note that Bill's solution probably only does what you want for positive numbers. For negative numbers you might want to add -0.5 to achieve the "conventional" symmetric rounding effect. Cheers, -Jan On Fri, 16 Mar 2007, Bill Luebkert wrote: > > Su, Yu (Eugene) wrote: > > I expect > > print sprintf("%.0f %.0f %.0f %.0f %.0f %.0f %.0f %.0f %.0f %.0f", 0.5, > > 1.5, 2.5, 3.5, 4.5, 5.5, > 6.5, 7.5, 8.5, 9.5); > > will give me > > 1 2 3 4 5 6 7 8 9 10 > > but instead I get > > 0 2 2 4 4 6 6 8 8 10 > > > > How to round a floating-point value to an integer value using (.5) up rule? > > I'd add .5 in the next place down : > > foreach (0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0) { > printf "%.1f => %.0f\n", $_, $_ + .05; > } > > 0.0 => 0 > 0.1 => 0 > 0.2 => 0 > 0.3 => 0 > 0.4 => 0 > 0.5 => 0 > 0.6 => 1 > 0.7 => 1 > 0.8 => 1 > 0.9 => 1 > 1.0 => 1 > > _______________________________________________ > Perl-Win32-Users mailing list > Perl-Win32-Users@listserv.ActiveState.com > To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs _______________________________________________ Perl-Win32-Users mailing list Perl-Win32-Users@listserv.ActiveState.com To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs