round a number to the nearest hundredth in ruby

To round a number to the nearest hundredth in Ruby, you can use the round method with the 2 argument for precision since you want to round to two decimal places (hundredths):

main.rb
num = 3.14159
rounded_num = num.round(2) # 3.14
48 chars
3 lines

Alternatively, you could use string formatting to achieve the same result:

main.rb
num = 3.14159
rounded_num = "%.2f" % num # "3.14"
50 chars
3 lines

Both approaches will round the number num to two decimal places, in this case resulting in 3.14.

gistlibby LogSnag