In Typescript, How to check if a string is Numeric

前端 未结 10 1167
耶瑟儿~
耶瑟儿~ 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条回答
  •  旧时难觅i
    2020-12-02 12:10

    Most of the time the value that we want to check is string or number, so here is function that i use:

    const isNumber = (n: string | number): boolean => 
        !isNaN(parseFloat(String(n))) && isFinite(Number(n));
    

    Codesandbox tests.

    const willBeTrue = [0.1, '1', '-1', 1, -1, 0, -0, '0', "-0", 2e2, 1e23, 1.1, -0.1, '0.1', '2e2', '1e23', '-0.1', ' 898', '080']
    
    const willBeFalse = ['9BX46B6A', "+''", '', '-0,1', [], '123a', 'a', 'NaN', 1e10000, undefined, null, NaN, Infinity, () => {}]
    

提交回复
热议问题