Ruby: Rounding float in Ruby
Solution 1:
Pass an argument to round containing the number of decimal places to round to
>> 2.3465.round
=> 2
>> 2.3465.round(2)
=> 2.35
>> 2.3465.round(3)
=> 2.347
Solution 2:
When displaying, you can use (for example)
>> '%.2f' % 2.3465
=> "2.35"
If you want to store it rounded, you can use
>> (2.3465*100).round / 100.0
=> 2.35
Solution 3:
you can use this for rounding to a precison..
//to_f is for float
salary= 2921.9121
puts salary.to_f.round(2) // to 2 decimal place
puts salary.to_f.round() // to 3 decimal place