ruby on rails 如何处理 NaN

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19154461/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:49:20  来源:igfitidea点击:

ruby on rails how to deal with NaN

ruby-on-railsrubyruby-on-rails-3ruby-on-rails-3.2ruby-on-rails-3.1

提问by Paul Phoenix

I have read few posts regarding NaNbut did not figure out how to deal with it in Ruby on Rails. I want to check a value if it is a NaNI want to replace it with Zero(0). I tried the following

我读过几篇关于NaN但没有弄清楚如何在 Ruby on Rails 中处理它的帖子。我想检查一个值是否是一个NaN我想用零(0)替换它。我尝试了以下

logger.info(".is_a? Fixnum #{percent.is_a? Fixnum}")

when percent has NaNit returns me false.

当百分比有NaN它返回我错误。

I have made few changes in the logger

我在记录器中做了一些更改

logger.info("Fixnum #{percent.is_a? Fixnum} percent #{percent}")

Output

输出

Fixnum false percent 94.44444444444444
Fixnum false percent NaN
Fixnum false percent 87.0

回答by falsetru

NaNis instance of Float. Use Float#nan?method.

NaN是 的实例Float。使用Float#nan?方法。

>> 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

更新

NaNcould also be an instance of BigDecimal:

NaN也可以是一个实例BigDecimal

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

or

或者

{Float::NAN => 0, BigDecimal::NAN => 0}.fetch(nan, nan)