I want to check whether a string entered is NAN in typescript. Currently I am doing like
if (isNaN(parseInt(input))) return "It's not a number."
This works fine if I enter @@@@ or #### but if I enter "444@@@@", this is not working.
I want to check whether a string entered is NAN in typescript. Currently I am doing like
if (isNaN(parseInt(input))) return "It's not a number."
This works fine if I enter @@@@ or #### but if I enter "444@@@@", this is not working.
parseInt
parses up to the first non-numeral in the input string, see MDN:
If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. parseInt truncates numbers to integer values. Leading and trailing spaces are allowed.
In this case, parseInt("444@@@@") === 444
, and 444
is not NaN
.
If you want to check if the entire string represents a valid number, use Number
instead:
if (isNaN(Number(input))) return "It's not a number."
Alternatively, use the unary plus operator to force a type conversion to number
(equivalent to calling Number
):
if (isNaN(+input)) return "It's not a number."
EDIT: Actually, isNaN
will do a type conversion anyway, so you could just as well call it directly:
if (isNaN(input)) return "It's not a number."