0

After some string manipulation I am left with a 4 character string that I will call

varString

I need to see if this string could be interpreted as a number. I have been using

if(isNaN(Number(varString)) ==  false){return true}

but I am wondering if

if(Number("varString").toString() == varString){return true}

would be better.

Is one of these solutions more efficient, or more likely to catch non-numbers than the other? I have not found a difference while testing but I may have missed something. Alternative solutions welcome.

Edit in response to possible duplicate: I already have two ways of determining if something is a string or number. I am asking which method is better and why.

Simon
  • 855
  • 9
  • 24
  • Possible duplicate of [Check whether variable is number or string in javascript](http://stackoverflow.com/questions/1303646/check-whether-variable-is-number-or-string-in-javascript) – Hunter McMillen Jan 04 '17 at 19:01
  • In the first one, no need for the `== false` check. Just do `if(!isNaN(Number(varString)))` – Andrew Li Jan 04 '17 at 19:01

3 Answers3

3

The second method will prove wrong for some cases, since Number will convert numbers starting with 0, but will save them in the form of a number, so a toString will not match the original string:

document.write(Number("0123").toString() == "0123")

Go with

return !isNaN(varString)

(a variation of the first one, and you dont need to parse with Number).

Uriel
  • 15,579
  • 6
  • 25
  • 46
2

There will be differences at least in these cases:

  • With "NaN"

    isNaN(Number("NaN")) === false; // false
    Number("NaN").toString() === "NaN"; // true
    
  • With "-0"

    isNaN(Number("-0")) === false; // true
    Number("-0").toString() === "-0"; // false
    
  • With space padded numbers

    isNaN(Number(" 1 ")) === false; // true
    Number(" 1 ").toString() === " 1 "; // false
    
  • With zero left-padded numbers

    isNaN(Number("01")) === false; // true
    Number("01").toString() === "01"; // false
    
  • With numbers starting or ending with decimal point

    isNaN(Number(".5")) === false; // true
    Number(".5").toString() === ".5"; // false
    
  • With huge or tiny numbers

    isNaN(Number("999999999999999999999")) === false; // true
    Number("999999999999999999999").toString() === "999999999999999999999"; // false
    
  • With non-huge and non-tiny numbers in exponential form

    isNaN(Number("1e1")) === false; // true
    Number("1e1").toString() === "1e1"; // false
    
  • With binary, octal or hex literals

    isNaN(Number("0xa")) === false; // true
    Number("0xa").toString() === "0xa"; // false
    
Oriol
  • 274,082
  • 63
  • 437
  • 513
0

In the second case you are parsing the number from string and converting it back to string. Obviously, it is less efficient

Pranay Kumar
  • 2,139
  • 1
  • 15
  • 15