1

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?

3 Answers 3

1

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'));

Sign up to request clarification or add additional context in comments.

3 Comments

Getting close, but notice is_number(null) == true
I know I'm expanding the scope of this function slightly, but notice: is_number(0) == false
@speedplane ok now check.
0

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)

Comments

0

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));
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.