Numeric.abs / round / ceil / floor / truncate
Methods for getting the absolute value of a number and rounding decimals. These methods work on both integers and floating-point numbers.
Syntax
# Returns the absolute value. number.abs # Rounds to the nearest integer (n specifies the number of decimal places). number.round number.round(n) # Rounds up (ceiling). number.ceil number.ceil(n) # Rounds down (floor). number.floor number.floor(n) # Truncates toward zero. number.truncate number.truncate(n)
Method List
| Method | Description |
|---|---|
| abs | Returns the absolute value of the number. Positive numbers are returned as-is; negative numbers are returned without the sign. |
| round | Returns the number rounded to the nearest integer. If n is specified, rounds to n decimal places. |
| ceil | Returns the number rounded up to the nearest integer. If n is specified, rounds up to n decimal places. |
| floor | Returns the number rounded down to the nearest integer. If n is specified, rounds down to n decimal places. |
| truncate | Truncates toward zero. For negative numbers, this produces a different result than floor. |
Sample Code
# abs: Get the absolute value.
puts (-5).abs # 5
puts 3.14.abs # 3.14
puts (-2.7).abs # 2.7
# round: Round to the nearest integer.
puts 3.14159.round # 3
puts 3.14159.round(2) # 3.14
puts 3.14159.round(4) # 3.1416
puts 2.5.round # 3 (rounds up)
# ceil: Round up.
puts 3.1.ceil # 4
puts (-3.1).ceil # -3 (rounds toward zero)
puts 3.14.ceil(1) # 3.2
# floor: Round down.
puts 3.9.floor # 3
puts (-3.9).floor # -4 (rounds away from zero)
puts 3.96.floor(1) # 3.9
# truncate: Truncate toward zero.
puts 3.9.truncate # 3
puts (-3.9).truncate # -3 (different from floor!)
# Practical example: Calculate tax (truncate to the nearest integer).
price = 1234
total = (price * 1.1).floor
puts "#{price} yen → with tax: #{total} yen" # 1234 yen → with tax: 1357 yen
Notes
Calling round, ceil, or floor without an argument returns an integer. Passing an argument n returns a floating-point number rounded to n decimal places. You can also pass a negative number to round at the integer level (e.g., 1234.round(-2) returns 1200).
Pay attention to behavior with negative numbers. floor(-3.9) returns -4 (toward negative infinity), ceil(-3.9) returns -3 (toward positive infinity), and truncate(-3.9) returns -3 (toward zero) — each producing a different result.
Floating-point numbers have internal representation errors, so 0.1 + 0.2 may not equal exactly 0.3. For financial calculations or other precision-sensitive work, use the BigDecimal class instead.
For type conversion of numbers, see number.to_i / to_f / to_s. For math functions, see Math.sqrt / log / sin / cos.
If you find any errors or copyright issues, please contact us.