namtax
namtax

Reputation: 2467

Round a number up in ruby

Just wondering how would i round the number "15.755" up to "15.76" in ruby.

I have tried the round method, but doesnt produce the result im looking for.

Thanks

Upvotes: 0

Views: 2267

Answers (1)

Michael Kohl
Michael Kohl

Reputation: 66837

Is this not what you want?

>> 15.755.round(2)
=> 15.76

Ah, you are probably using 1.8 (why btw?). There you can do the following:

>> (15.755 * 100).round / 100.0
=> 15.76

You could wrap that up in a helper function:

def round(n, precision)
  raise "Precision needs to be >= 0" if precision < 0
  power_of_ten = 10 ** precision
  (n * power_of_ten).round / power_of_ten.to_f
end

round(15.755, 2) #=> 15.76

Upvotes: 4

Related Questions