【问题标题】:How to default to zero if the value is nil如果值为 nil,如何默认为零
【发布时间】:2012-11-25 09:05:49
【问题描述】:

如果 some_float 为 nil,我希望结果为 0。我该怎么做?

some_float = 9.238
or 
some_float = nil

some_float.round(2)

【问题讨论】:

标签: ruby


【解决方案1】:

在回合前拨打.to_f

some_float.to_f.round(2)

因为当你在 nil 上调用 to_f 时,它会返回 0.0

9.238.to_f.round(2) # => 9.24
nil.to_f.round(2) # => 0.0

【讨论】:

    【解决方案2】:

    选项 1:

    x = some_float ? some_float.round(2) : 0.0
    

    选项 2(Ruby >= 2.3.0):

    x = some_float&.round(2) || 0.0
    

    【讨论】:

      猜你喜欢
      • 2017-12-05
      • 2018-01-04
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      • 2019-09-07
      • 2017-03-26
      • 1970-01-01
      • 2019-10-03
      相关资源
      最近更新 更多