Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if number is NaN

Tags:

ruby

nan

I'm trying to check if a variable I have is equals to NaN in my Ruby on Rails application.

I saw this answer, but it's not really useful because in my code I want to return 0 if the variable is NaN and the value otherwise:

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

The problem is that if the number is not a NaN I get this error:

NoMethodError: undefined method `nan?' for 10:Fixnum

I can't check if the number is a Float instance because it is in both cases (probably, I'm calculating an average). What can I do? It is strange only to me that a function to check if a variable is equals to NaN is avaible only to NaN objects?

like image 358
ste Avatar asked Jul 12 '16 11:07

ste


People also ask

How do you check if a number is NaN or not?

The Number. isNaN() method returns true if the value is NaN , and the type is a Number.

Is NaN == NaN?

Yeah, a Not-A-Number is Not equal to itself. But unlike the case with undefined and null where comparing an undefined value to null is true but a hard check(===) of the same will give you a false value, NaN's behavior is because of IEEE spec that all systems need to adhere to.

Is not NaN JavaScript?

The isNaN() function is used to check whether a given value is an illegal number or not. It returns true if value is a NaN else returns false. It is different from the Number. isNaN() Method.

Is NaN True or false?

A falsy value is something which evaluates to FALSE, for instance when checking a variable. There are only six falsey values in JavaScript: undefined , null , NaN , 0 , "" (empty string), and false of course.


2 Answers

I found this answer while duckducking for something that is not either NaN or Infinity (e.g., something that is a finite number). Hence I'll add my discovery here for next googlers.

And as always in ruby, the answer was just to type my expectation while searching in the Float documentation, and find finite?

n = 1/0.0 #=> Infinity
n.nan? #=> false
n.finite? #=> false
like image 82
Ulysse BN Avatar answered Sep 24 '22 20:09

Ulysse BN


The best way to avoid this kind of problem is to rely on the fact that a NaN isn't even equal to itself:

a = 0.0/0.0
a != a
# -> True !

This is likely not going to be an issue with any other type.

like image 28
Vincent Fourmond Avatar answered Sep 23 '22 20:09

Vincent Fourmond