Why is angular.isNumber() not working as expected?

前端 未结 3 1914
暗喜
暗喜 2021-01-02 03:10

It appears as if AngularJS\'s angular.isNumber is not working. It doesn\'t work with strings that are numbers. Am I doing something wrong? Should I just use

相关标签:
3条回答
  • 2021-01-02 03:40

    In JavaScript, typeof NaN === 'number'.

    If you need to recognise a String as a Number, cast it to Number, convert back to String and compare this against the input, for example.

    function stringIsNumber(s) {
        var x = +s; // made cast obvious for demonstration
        return x.toString() === s;
    }
    
    stringIsNumber('95.55'); // true
    stringIsNumber('foo'); // false
    // still have
    stringIsNumber('NaN'); // true
    
    0 讨论(0)
  • 2021-01-02 03:55

    I was working on the same problem and I was trying to work around that edge case. So I created a slightly different approach.

    FIDDLE

    function isStringNumber(str) {
      var parsed = parseFloat(str);
      var casted = +str;
      return parsed === casted  && !isNaN(parsed) && !isNaN(casted);
    }
    
    0 讨论(0)
  • 2021-01-02 04:02

    Use it as below,

    angular.isNumber(eval('99.55'))
    

    for other expressions also we may use eval(input).

    Note: eval() is a javascript method

    Edit: It is not recommended to use eval(), as document says Never use eval()!

    Thanks @Diogo Kollross

    0 讨论(0)
提交回复
热议问题