In Typescript, How to check if a string is Numeric

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

    I would choose an existing and already tested solution. For example this from rxjs in typescript:

    function isNumeric(val: any): val is number | string {
      // parseFloat NaNs numeric-cast false positives (null|true|false|"")
      // ...but misinterprets leading-number strings, particularly hex literals ("0x...")
      // subtraction forces infinities to NaN
      // adding 1 corrects loss of precision from parseFloat (#15100)
      return !isArray(val) && (val - parseFloat(val) + 1) >= 0;
    }
    

    rxjs/isNumeric.ts

    Without rxjs isArray() function and with simplefied typings:

    function isNumeric(val: any): boolean {
      return !(val instanceof Array) && (val - parseFloat(val) + 1) >= 0;
    }
    

    You should always test such functions with your use cases. If you have special value types, this function may not be your solution. You can test the function here.

    Results are:

    enum         : CardTypes.Debit   : true
    decimal      : 10                : true
    hexaDecimal  : 0xf10b            : true
    binary       : 0b110100          : true
    octal        : 0o410             : true
    stringNumber : '10'              : true
    
    string       : 'Hello'           : false
    undefined    : undefined         : false
    null         : null              : false
    function     : () => {}          : false
    array        : [80, 85, 75]      : false
    turple       : ['Kunal', 2018]   : false
    object       : {}                : false
    

    As you can see, you have to be careful, if you use this function with enums.

提交回复
热议问题