In Typescript, How to check if a string is Numeric

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

    Update 2

    This method is no longer available in rxjs v6

    I'm solved it by using the isNumeric operator from rxjs library (importing rxjs/util/isNumeric

    Update

    import { isNumeric } from 'rxjs/util/isNumeric';

    . . .

    var val = "5700";
    if (isNumeric(val)){
       alert("it is number !");
    }
    
    0 讨论(0)
  • 2020-12-02 12:21

    My simple solution here is:

    const isNumeric = (val: string) : boolean => {
       return !isNaN(Number(val));
    }
    
    // isNumberic("2") => true
    // isNumeric("hi") => false;
    
    0 讨论(0)
  • 2020-12-02 12:22

    For full numbers (non-floats) in Angular you can use:

    if (Number.isInteger(yourVariable)) { ... }

    0 讨论(0)
  • 2020-12-02 12:31
    function isNumber(value: string | number): boolean
    {
       return ((value != null) &&
               (value !== '') &&
               !isNaN(Number(value.toString())));
    }
    
    0 讨论(0)
提交回复
热议问题