HiveBrain v1.2.0
Get Started
← Back to all entries
snippettypescriptCritical

In Typescript, How to check if a string is Numeric

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
typescripthowchecknumericstring

Problem

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

Solution

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

Code Snippets

Number('1234') // 1234
Number('9BX9') // NaN
+'1234' // 1234
+'9BX9' // NaN
isNaN(+maybeNumber) // returns true if NaN, otherwise false

Context

Stack Overflow Q#23437476, score: 609

Revisions (0)

No revisions yet.