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?
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?
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"
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.