I’m hoping there’s something in the same conceptual space as the old VB6 IsNumeric() function?
I’m hoping there’s something in the same conceptual space as the old VB6 IsNumeric()
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
2nd October 2020: note that many bare-bones approaches are fraught with subtle bugs (eg. whitespace, implicit partial parsing, radix, coercion of arrays etc.) that many of the answers here fail to take into account. The following implementation might work for you, but note that it does not cater for number separators other than the decimal point "
.":To check if a variable (including a string) is a number, check if it is not a number:
This works regardless of whether the variable content is a string or number.
Examples
Of course, you can negate this if you need to. For example, to implement the
IsNumericexample you gave:To convert a string containing a number into a number:
Only works if the string only contains numeric characters, else it returns
NaN.Examples
To convert a string loosely to a number
Useful for converting ’12px’ to 12, for example:
Examples
Floats
Bear in mind that, unlike
+num,parseInt(as the name suggests) will convert a float into an integer by chopping off everything following the decimal point (if you want to useparseInt()because of this behaviour, you’re probably better off using another method instead):Empty strings
Empty strings may be a little counter-intuitive.
+numconverts empty strings or strings with spaces to zero, andisNaN()assumes the same:But
parseInt()does not agree: