Ruby: Rounding float in Ruby Ruby: Rounding float in Ruby ruby ruby

Ruby: Rounding float in Ruby


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


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


you can use this for rounding to a precison..

//to_f is for floatsalary= 2921.9121puts salary.to_f.round(2) // to 2 decimal place                   puts salary.to_f.round() // to 3 decimal place