ruby on rails how to deal with NaN

前端 未结 1 2001
失恋的感觉
失恋的感觉 2021-01-07 16:10

I have read few posts regarding NaN but did not figure out how to deal with it in Ruby on Rails. I want to check a value if it is a NaN I want to r

相关标签:
1条回答
  • 2021-01-07 16:31

    NaN is instance of Float. Use Float#nan? method.

    >> nan = 0.0/0 # OR nan = Float::NAN
    => NaN
    >> nan.class
    => Float
    >> nan.nan?
    => true
    >> nan.is_a?(Float) && nan.nan?
    => true
    >> (nan.is_a?(Float) && nan.nan?) ? 0 : nan
    => 0
    

    UPDATE

    NaN could also be an instance of BigDecimal:

    ((nan.is_a?(Float) || nan.is_a?(BigDecimal)) && nan.nan?) ? 0 : nan
    

    or

    {Float::NAN => 0, BigDecimal::NAN => 0}.fetch(nan, nan)
    
    0 讨论(0)
提交回复
热议问题