Skip to content

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

instance method

Float#truncate

float.truncate([ndigits]) → integer or float

Returns float truncated (toward zero) to a precision of ndigits decimal digits (default: 0).

When the precision is negative, the returned value is an integer with at least ndigits.abs trailing zeros.

Returns a floating point number when ndigits is positive, otherwise returns an integer.

Example
2.8.truncate           #=> 2
(-2.8).truncate        #=> -2
1.234567.truncate(2)   #=> 1.23
34567.89.truncate(-2)  #=> 34500

Note that the limited precision of floating point arithmetic might lead to surprising results:

Example
(0.3 / 0.1).truncate  #=> 2 (!)
See also #to_s #zero? #to_r also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.1