In Typescript, How to check if a string is Numeric

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

    Whether a string can be parsed as a number is a runtime concern. Typescript does not support this use case as it is focused on compile time (not runtime) safety.

    0 讨论(0)
  • 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, () => {}]
    
    0 讨论(0)
  • 2020-12-02 12:11

    Simple answer: (watch for blank & null)

    isNaN(+'111') = false;
    isNaN(+'111r') = true;
    isNaN(+'r') = true;
    isNaN(+'') = false;   
    isNaN(null) = false;   
    

    https://codepen.io/CQCoder/pen/zYGEjxd?editors=1111

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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!

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题