There are some surprises for the JS beginner in number checking. I take a crack at three good ways to go about doing this.
By Matthew Malinowski, 2013-05-28
idea might be to just check
typeof and be done with it:
For some situations, this is all you need.
But, remember: there are three (perhaps unexpected, at least to me at first) values that have a typeof 'number': positive Infinity, negative Infinity, and NaN. If you want to exclude these values, you'll also need to check for finitude:
Or, if you have access to our above isNumber function and Aren't Repeating Yourself:
isFinite is going to exclude positive Infinity, negative Infinity, and NaN, none
of which are finite. This function will reasonably tell you if something is a
number... except if your input is formatted as a string.
What does this mean?
isFiniteNumber(12) are both going to
isFiniteNumber('12') won't, because
num is going to be
string in both cases.
In this case I might say: tough. Stuff that produces numbers that get fed to these functions should be producing them as numbers, not as numeric strings. But, I guess sometimes you just need to parse a string for numbers. Around version 1.7, jQuery added isNumeric , which does just this as it's checking the numberness of your input:
isFinite is here for the same reason as I explained above, but that first part
parseFloat parses a string for numeric characters and returns a floating point
number. It's worth reading about on MDN.
The tl;dr is:
"If [parseFloat()] encounters a character other than a sign (+ or -), numeral (0-9), a decimal point, or an exponent, it returns the value up to that point and ignores that character and all succeeding characters. Leading and trailing spaces are allowed. If the first character cannot be converted to a number, parseFloat returns NaN."
So: parseFloat() pulls a number out of your string, if possible. If the first
character is not in its acceptable group, it returns NaN.
!isNaN is in our
function to check for this result.
You've now got three ways to check if something is a number.
isNumberto see if an input is any number value, including negative Infinity, positive Infinity, and NaN.
isFiniteNumberto see if an input is any number value except negative Infinity, positive Infinity, and NaN.
isNumericto see if an input might be a numeric string that, when converted to a number, is any number value except negative Infinity, positive Infinity, and NaN.