Reputation: 16121
How do you determine if a string represents a number?
The straightforward and potentially naive way is this:
function is_number(my_str) {
return !isNaN(parseInt(my_str));
}
However, the above does not work. Notice that the following all return true:
is_number("3, 4, 5");
is_number("3, (123)");
is_number("3, 123)");
is_number("3, (123) (and foo bar)");
is_number("3 apples and 2 oranges");
The issue is that parseInt
seems to only look at the first word. Any idea on a more comprehensive solution here?
Upvotes: 1
Views: 47
Reputation: 4913
Here's my regular-expression based effort:
function isNumber (string) {
return /^-?[0-9]+(?:\.[0-9]+)?(?:[eE][-+]?[0-9]+)?$/.test(string);
}
Includes support for leading sign, decimal places and exponent.
If it returns true
, the string can be converted to a number using JSON.parse
:
function isNumber (string) {
return /^-?[0-9]+(?:\.[0-9]+)?(?:[eE][-+]?[0-9]+)?$/.test(string);
}
function convertNumber (string) {
if (isNumber(string)) {
return JSON.parse(string);
}
}
[
'0',
'1.2',
'-3.4',
'5.6789e100',
'0.1e-100',
'0.1e+100',
].forEach(string => {
console.log(`isNumber('${string}'):`, isNumber(string));
console.log(`typeof convertNumber('${string}'):`, typeof convertNumber(string));
});
Upvotes: 0
Reputation: 36574
You can use Number().
parseInt
and parseFloat
converts String
to Number if first character is a number. But Number()
checks for whole String
.Number return NaN
if whole string is not number
function is_number(my_str) {
return !isNaN(Number(my_str)) && Boolean(my_str) || my_str == 0;
}
console.log(is_number("3, 4, 5"));
console.log(is_number("3, (123)"));
console.log(is_number("3, 123)"));
console.log(is_number("3, (123) (and foo bar)"));
console.log(is_number("3 apples and 2 oranges"));
console.log(is_number(null));
console.log(is_number(undefined));
console.log(is_number(0));
console.log(is_number('0'));
Upvotes: 1
Reputation: 37755
All you need is Number
console.log(Number("3, 4, 5") || false)
console.log(Number("3, (123)") || false)
console.log(Number("3, 123)") || false)
console.log(Number('123') || false)
Upvotes: 0