0

What is the most reliable way to check if a string is a number or not?

 var checkForNumber = (arg) => {
   if (typeof arg === 'number') {
     return arg + ' is a number'
   } else if (Number(arg)) {
     return arg + ' is a number'
   }
  return 'Not a number';
 };

 checkForNumber('a')

Jeena
  • 4,193
  • 3
  • 9
  • 19
  • Well, if the arg is a **string**, as your intro line says, the first if will always be false. – Taplar Feb 05 '20 at 18:50
  • You don't need `typeof` since `Number(25)` returns `25` (truthy) anyways. If `arg` is in fact always a string, then `Number(arg)` is sufficient. Otherwise (e.g. `arg = {val: 25}`), you'll need more checks. – junvar Feb 05 '20 at 18:51
  • In case if you don't know, `NaN` is also a number. – Addis Feb 05 '20 at 18:54
  • ```if (isNaN(parseFloat(number)) && isFinite(number)) return '';``` ===> will this be the right way to check whether the number that is passed in is a number or string. If its not then return an empty string – Jeena Feb 05 '20 at 19:17

2 Answers2

0

Given that the constructor of Number() will return NaN if invalid, I think this might be a good way to get a boolean value as to whether a number is valid or not:

function isNum(num) {
   return (
      !isNaN(num) && 
      (parseInt(num) == num || parseFloat(num) == num)
   );
}

console.log('"1"', isNum('1'));
console.log('1', isNum(1));
console.log('"a"', isNum('a'));
console.log('empty string', isNum(''));
console.log('object', isNum({}));
console.log('undefined', isNum(undefined));
console.log('false', isNum(false));
console.log('true', isNum(true));
console.log('[]', isNum([]));
console.log('PI short string', isNum('3.14'));
console.log('PI short float', isNum(3.14));

console.log('PI long', isNum(3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679));

You have to also check if boolean or array though, because they will come back as a number. I am doing that by comparing the output of parseInt.

Jeremy Harris
  • 24,318
  • 13
  • 79
  • 133
0

The best way that I consider to check numbers is the function isNaN(), "is Not a Number" the opposite of "Is a Number"

>isNaN(1)
 false
>isNaN('1')
 false
>isNaN('1e')
 true
>isNaN('1.1')
 false
>isNaN('1,1')
 true
>isNaN('0000001')
 false
>isNaN('f12f')
 true

You should use this function as negated: !isNaN()