In Typescript, How to check if a string is Numeric

user3509546 picture user3509546 · May 2, 2014 · Viewed 208.3k times · Source

In Typescript, this shows an error saying isNaN accepts only numeric values

isNaN('9BX46B6A')

and this returns false because parseFloat('9BX46B6A') evaluates to 9

isNaN(parseFloat('9BX46B6A'))

I can still run with the error showing up in Visual Studio, but I would like to do it the right way.

Currently, I have written this modified function -

static isNaNModified = (inputStr: string) => {
    var numericRepr = parseFloat(inputStr);
    return isNaN(numericRepr) || numericRepr.toString().length != inputStr.length;
}

Answer

C Snover picture C Snover · May 3, 2014

The way to convert a string to a number is with Number, not parseFloat.

Number('1234') // 1234
Number('9BX9') // NaN

You can also use the unary plus operator if you like shorthand:

+'1234' // 1234
+'9BX9' // NaN

Be careful when checking against NaN (the operator === and !== don't work as expected with NaN). Use:

 isNaN(+maybeNumber) // returns true if NaN, otherwise false