Check if number is NaN in Ruby on Rails -


i'm trying check if variable have equals nan in ruby on rails application.

i saw answer, it's not useful because in code want return 0 if variable nan , value otherwise:

 return (average.nan ? 0 : average.round(1)) 

the problem if number not nan error:

nomethoderror: undefined method `nan?' 10:fixnum 

i can't check if number float instance because in both cases (probably, i'm calculating average). can do? strange me function check if variable equals nan avaible nan objects?

quickest way use this:

under_the_test.to_f.nan? # gives true/false e.g.: 123.to_f.nan? # => false (123/0.0).to_f.nan? #=> true 

also note floats have #nan? method defined on them, that's reason why i'm using #to_f in order convert result float first.

tip: if have integer calculation potentially can divide 0 not work:

(123/0).to_f.nan?  

because both 123 , 0 integers , throw zerodivisionerror, in order overcome issue float::nan constant can useful - example this:

return float::nan if divisor == 0 return x / divisor 

Comments

Popular posts from this blog

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.Error occurred in starting fork -

windows - Debug iNetMgr.exe unhandle exception System.Management.Automation.CmdletInvocationException -

configurationsection - activeMq-5.13.3 setup configurations for wildfly 10.0.0 -