Ruby Language Rounding Numbers


Example

The round method will round a number up if the first digit after its decimal place is 5 or higher and round down if that digit is 4 or lower. This takes in an optional argument for the precision you're looking for.

4.89.round        # => 5
4.25.round        # => 4
3.141526.round(1) # => 3.1
3.141526.round(2) # => 3.14
3.141526.round(4) # => 3.1415

Floating point numbers can also be rounded down to the highest integer lower than the number with the floor method

4.9999999999999.floor # => 4

They can also be rounded up to the lowest integer higher than the number using the ceil method

4.0000000000001.ceil  # => 5