-2

I'm trying to round a float value as follows:

(0.11 + 0.22 + 0.23 / 3).round(2)

Does anyone know if there is other effective way to round up?

Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
diya
  • 6,938
  • 9
  • 39
  • 55
  • Wait, where's the `OrderedHash`? The problem can't be in the segment you showed us, unless someone redefined `Float#+`. – Amadan Dec 05 '12 at 04:03
  • 1
    I'm guessing those numbers are not hardcoded. Where do they come from? – Rodrigo_at_Ximera Dec 05 '12 at 04:04
  • Why did you remove the error message? Like this the question doesn't make sense. `(0.11 + 0.22 + 0.23 / 3).round(2)` works fine. – Mischa Dec 05 '12 at 04:09
  • Actually it's not a problem, am asking that Is other effective way to round a float value instead of doing (0.11 + 0.22 + 0.23 / 3).round(2) this ! – diya Dec 05 '12 at 04:13
  • 2
    So… what's the problem? Is it just that you think calling `round` is too complicated? – Andrew Marshall Dec 05 '12 at 04:15
  • no, its not too complicated, i was just thinking if there is any other way ! – diya Dec 05 '12 at 04:22

2 Answers2

2

The main ways to round a floating point number in Ruby are via the Float#round method or the String#% (format) operator. For example:

f = (0.11 + 0.22 + 0.23 / 3) # => 0.4066666666666667
f.round(2)  # =>  0.41
"%.02f" % f # => "0.41"
maerics
  • 151,642
  • 46
  • 269
  • 291
1

If you always want to round up and never down, you can do this:

(0.411 * 100).ceil / 100.0 # => 0.42

Otherwise just use round. Or use the string formatter if you don't mind your float turning into a string.

Mischa
  • 42,876
  • 8
  • 99
  • 111