In Typescript, How to check if a string is Numeric
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;
}
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
Update 2
This method is no longer available in rxjs v6
I'm solved it by using the isNumeric operator from rxjs library (importing rxjs/util/isNumeric
Update
import { isNumeric } from 'rxjs/util/isNumeric';
. . .
var val = "5700";
if (isNumeric(val)){
alert("it is number !");
}
function isNumber(value: string | number): boolean
{
return ((value != null) &&
(value !== '') &&
!isNaN(Number(value.toString())));
}
You can use the Number.isFinite()
function:
Number.isFinite(Infinity); // false
Number.isFinite(NaN); // false
Number.isFinite(-Infinity); // false
Number.isFinite('0'); // false
Number.isFinite(null); // false
Number.isFinite(0); // true
Number.isFinite(2e64); // true
Note: there's a significant difference between the global function isFinite()
and the latter Number.isFinite()
. In the case of the former, string coercion is performed - so isFinite('0') === true
whilst Number.isFinite('0') === false
.
Also, note that this is not available in IE!