How to round float value to the nearest n decimal places in Ruby

Overview

The round() method can be used to round a number to a specified number of decimal places in Ruby. We can use it without a parameter (round()) or with a parameter (round(n)).

n here means the number of decimal places to round it to.

Syntax

# default rounding
float_value.round
# to n decimal places
float_value.round(n)

Parameters

float_value: This is the float value we want to round.

n: Represents the number of decimal places we want to round the float_value to.

Return value

The value returned is a float rounded to the nearest value with a precision of n decimal digits or 0 digit if no parameter is passed.

Example

# create some float values
f1 = 2.3333545
f2 = 1.4445567
f3 = 100.12711
f4 = -0.8889
# round float values
# and print results
puts f1.round # to 0 decimal place
puts f2.round(3) # to 3 decimal places
puts f3.round(1) # to 1 decimal place
puts f4.round(2) # to 2 decimal places

Explanation

  • Line 2–5: We define some float values that we want to round off.
  • Linew 9–12: We call the round() method on the already defined float values and print the results.

Free Resources