Skip to content

End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

Integer#round

round(ndigits= 0, half: :up) → integer

Returns self rounded to the nearest value with a precision of ndigits decimal digits.

When ndigits is negative, the returned value has at least ndigits.abs trailing zeros:

Example
555.round(-1)      # => 560
555.round(-2)      # => 600
555.round(-3)      # => 1000
-555.round(-2)     # => -600
555.round(-4)      # => 0

Returns self when ndigits is zero or positive.

Example
555.round     # => 555
555.round(1)  # => 555
555.round(50) # => 555

If keyword argument half is given, and self is equidistant from the two candidate values, the rounding is according to the given half value:

  • :up or nil: round away from zero:

    Example
    25.round(-1, half: :up)      # => 30
    (-25).round(-1, half: :up)   # => -30
    
  • :down: round toward zero:

    Example
    25.round(-1, half: :down)    # => 20
    (-25).round(-1, half: :down) # => -20
    
  • :even: round toward the candidate whose last nonzero digit is even:

    Example
    25.round(-1, half: :even)    # => 20
    15.round(-1, half: :even)    # => 20
    (-25).round(-1, half: :even) # => -20
    

Raises and exception if the value for half is invalid.

Related: Integer#truncate.

See also #remainder #size #rationalize #succ also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.0