In Typescript, How to check if a string is Numeric

前端 未结 10 1137
耶瑟儿~
耶瑟儿~ 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:15

    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
    

提交回复
热议问题