In Typescript, How to check if a string is Numeric
Update
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
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())));
}
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
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!