The guy asked to round a number, the simplest way
is (my highschool teacher would be proud now..):
$rounded = int ( $orig + 0.5 )
This approach floors any decimal portion less than 0.5, and rounds up (in value) any decimal portion greater than .5. That means the following:
1.1 rounds to 1.0.
1.5 rounds to 2.0.
-1.1 rounds to 1.0.
-1.5 rounds to 1.0.
$rounded = int ( $orig + 0.5 ) assumes $rounded is positive.
More generally: use POSIX; $rounded = floor ( $orig + 0.5 ) or $rounded = sprintf( "%.f" , $orig ) to properly handle the half-way case
See also `perldoc -q round`
For scientific applications requiring the use of significant
figures ("sig figs"), I strongly recommend the
Math::SigFigs module. Unfortunately, the
CPAN testers still haven't cleared it for Windows
print FormatSigFigs($number, $digits);
POSIX probably has an appropriate routine that'll do just that. You could also try using sprintf with the appropriate %0.2f (or whatever precision you're looking for). finally (TMTOWTDI), you could use the int keyword to truncate it, which might be more effective. for example, to generate dice rolls:
I was looking for a ceil(x,y) function similar to what exists in excel, where x is the thing to round, and y is "significance" according to Excel v9 (Office 2000), I prefer to think of it as "interval".
But, I was also intrigued by several of the other answers given (found via supersearch), and then in a fit of playing around, I created several variations below.
My personal restrictions were to use math operations, and not rely on other modules. This eliminated the printf and POSIX answers.
So, I hadn't thought much about negative numbers. Is it mathematically correct for the ceiling function to go to the next more negative number (to the left on a number line) or to truncate (ie int) a negative number (move toward the right on a number line)?
I think the rounding functions for negative numbers are correct (don't need adjusting), you're simply moving toward the nearest whole number...
As further discussed below, the code did originally have issues, the code in the answer above has now been replaced by working code.
I think you mean int?(been a while since I used pascal).
Div was the divisor operation. The result being not a
rounded down number, but the divisor of the operation.
5 div 2 = 2
meaining 5/2 = 2 remainder 1 .
Div returns the 2, Mod returns the 1.
Admittedly this is irrelivant to the origonal question,