In Typescript, How to check if a string is Numeric

前端 未结 10 1133
耶瑟儿~
耶瑟儿~ 2020-12-02 11:38

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

isNaN(\'9BX46B6A\')

and this returns false because parseF

10条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-02 12:14

    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!

提交回复
热议问题