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

Float#round

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

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

When ndigits is non-negative, returns a float with ndigits after the decimal point (as available):

Example
f = 12345.6789
f.round(1) # => 12345.7
f.round(3) # => 12345.679
f = -12345.6789
f.round(1) # => -12345.7
f.round(3) # => -12345.679

When ndigits is negative, returns an integer with at least ndigits.abs trailing zeros:

Example
f = 12345.6789
f.round(0)  # => 12346
f.round(-3) # => 12000
f = -12345.6789
f.round(0)  # => -12346
f.round(-3) # => -12000

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
    2.5.round(half: :up)      # => 3
    3.5.round(half: :up)      # => 4
    (-2.5).round(half: :up)   # => -3
    
  • :down: round toward zero:

    Example
    2.5.round(half: :down)    # => 2
    3.5.round(half: :down)    # => 3
    (-2.5).round(half: :down) # => -2
    
  • :even: round toward the candidate whose last nonzero digit is even:

    Example
    2.5.round(half: :even)    # => 2
    3.5.round(half: :even)    # => 4
    (-2.5).round(half: :even) # => -2
    

Raises and exception if the value for half is invalid.

Related: Float#truncate.

See also #rationalize #to_d #quo #to_f also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.0