Reputation: 15341
I would like to have the result as 0 if some_float is nil. How do I do that?
some_float = 9.238
or
some_float = nil
some_float.round(2)
Upvotes: 5
Views: 1639
Reputation: 67870
Option 1:
x = some_float ? some_float.round(2) : 0.0
Option 2 (Ruby >= 2.3.0):
x = some_float&.round(2) || 0.0
Upvotes: 2
Reputation: 230346
Just call a .to_f
before round
some_float.to_f.round(2)
Because when you call to_f
on nil, it'll return 0.0
9.238.to_f.round(2) # => 9.24
nil.to_f.round(2) # => 0.0
Upvotes: 16