I came across the goog.math.isFiniteNumber
function in the Google Closure Library. What it does is checking whether a given number is both finite and not NaN<
isNaN() returns true if the argument is not a number or if the argument is a non-numeric value such as a string or an object.Otherwise, It returns false.
Example: isNaN(0/0) =>true;
isNaN(2-1) =>false;
isFinite() returns true if the argument is a number other than NaN,Infinity or -Infinity.Otherwise, It returns false.
Example: isFinite("2000") =>false;
isFinite(200/2) =>true;`
Probably for the same reason that I have implemented (isfinite(num) && isfinite(-num))
- I was getting errors from mysql complaining about putting "-nan" into the database even though I had a check for isfinite(field)
...
A useful article on this subject is http://jacksondunstan.com/articles/983 which provides an optimization ((d*0.0)==0.0)
If isFinite
worked the way isFiniteNumber
did, then there would be no reason to write isFiniteNumber. There's probably some browser out there somewhere that treats NaN as finite.
you might reason out [Why?] after reading this:
NaN doesn't check if the passed value is infinite or not - it checks if the input val evaluates into a "Type: Number" end-result. Because isNaN(string) is accepted, so the: isNaN("3.14") //false (which means true, the given token is duck converted into a type Number successfully )
You may understand that the input value may happen to be an unresolved brute number, even a math operation as simple as: (x/y); which in turn might yield a (+/-infinity) number.
Here x=1, y=0; meaning (1/0).Then isNaN(x/y) will first evaluate to isNaN(1/0); then to isNaN(infinity) //false. Since (1/0)=infinity is of type: "number" ie typeof(1/0) //"number" isNaN should and will return false.
You don't want to put "infinity" where an end result number is expected.
The only difference is this:
!isNan(1/0) // --> true
isFinite(1/0) // --> false
isNaN checks whether the argument is a number or not. The Infinities (+/-) are also numerical, thus they pass the isNaN check, but don't pass the isFinite check.
** Note that any string which can be parsed as a number ("2", "3.14") will cause isNaN to return false.
Hope this helps.
PS: The answer given by user1170379 was very nearly perfect.