in reply to Re^2: Rounding off numbers
in thread Rounding off numbers

Hello jmichae3, and welcome to the Monastery!

As swampyankee said, int($x + 0.5) correctly rounds $x to an integer, provided that $x is non-negative.

So, for example, if you have 2 * 4.5 and want to make sure this comes out to 9, use:

19:27 >perl -wE "my $x = 2 * 4.5; my $y = int($x + 0.5); say $y;" 9 19:28 >

This is useful, because for some values (and on some machines), a calculation like 2 * 4.5 might come out as 8.99999999998. But with the formula: add 0.5 and truncate, that’s OK now:

19:28 >perl -wE "my $x = 8.99999999998; my $y = int($x + 0.5); say $y; +" 9 19:30 >

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,