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
Post a Comment