October 30, 2023
isNaN (stands for "is Not a Number") function.
However, there's a caveat.
isNaN will return
false for some non-numeric values, such as
null or an empty string. So, it's not a foolproof method.
Using a regular expression
A more robust way is to use a regular expression that matches valid number patterns.
This method is more accurate than
isNaN, as it specifically matches strings that are valid representations of numbers.
parseInt to convert strings into numbers. If the string isn't a valid number, they will return
parseFloat will accept any string that starts with a number and ignores non-numeric characters that follow. If strict validation is needed, it's better to use a combination of methods.
Edge cases with leading/trailing spaces
Often, input strings might come with leading or trailing spaces. Depending on your needs, you might handle them by trimming the string or by modifying the regular expression.
Another approach to determine if a string is a number is using the built-in
Number function. If the string isn't a valid number representation, it will return
Checking for hexadecimal, octal, and binary
0x), octal (prefixed with
0o), and binary (prefixed with
0b) literals. Depending on your requirements, you might consider these as valid numbers or not.
Considerations when working with large numbers
For very large or precise numbers, consider using libraries like
BigInt or third-party solutions such as bignumber.js for more precision.
Number can return
Infinity for very large numbers. You might want to treat this separately based on your use-case.
How to Truncate Date in MySQL