parseInt('5aab4') //5
// I expect the output is NaN.
My logic fails, due to parseInt. I assume that parseInt always returns NaN, when the input contains a letter?
parseInt('5aab4') //5
// I expect the output is NaN.
My logic fails, due to parseInt. I assume that parseInt always returns NaN, when the input contains a letter?
No, parseInt()
allows "garbage" (non-number) characters after some numeric characters. The parseFloat()
function has the same "feature".
If you want to get a number, you can use Number("123")
or simply the +
unary operator. However those accept any JavaScript number, including ones with fractional parts or numbers in scientific notation. But those methods will fail and give NaN
if the string input is not a valid numeric constant.
You could do something like
if (+someString === Math.floor(+someString))
I guess.
edit — a comment notes that you'd also want to check the degenerate case of an empty or all-space string too. A simple regular expression (/^\d+$/
) followed by a sanity check that it's not 200 digits long (amonth possibly other things) is another alternative.
If you were wanting to check NaN
another way would be to test it with isNaN()
.
isNaN()
will return a boolean giving you a verification for a given input.
parseInt('5aab4') //5
isNaN('5aab4') // true