snippettypescriptCritical
In Typescript, How to check if a string is Numeric
Viewed 0 times
typescripthowchecknumericstring
Problem
In Typescript, this shows an error saying isNaN accepts only numeric values
and this returns false because
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 -
isNaN('9BX46B6A')and this returns false because
parseFloat('9BX46B6A') evaluates to 9isNaN(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
You can also use the unary plus operator if you like shorthand:
Be careful when checking against NaN (the operator
Number, not parseFloat.Number('1234') // 1234
Number('9BX9') // NaNYou can also use the unary plus operator if you like shorthand:
+'1234' // 1234
+'9BX9' // NaNBe careful when checking against NaN (the operator
=== and !== don't work as expected with NaN). Use:isNaN(+maybeNumber) // returns true if NaN, otherwise falseCode Snippets
Number('1234') // 1234
Number('9BX9') // NaN+'1234' // 1234
+'9BX9' // NaNisNaN(+maybeNumber) // returns true if NaN, otherwise falseContext
Stack Overflow Q#23437476, score: 609
Revisions (0)
No revisions yet.