Kevin Beal Kevin Beal - 1 year ago 125
AngularJS Question

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

It appears as if AngularJS's

is not working. It doesn't work with strings that are numbers. Am I doing something wrong? Should I just use

angular.isNumber('95.55') == false
angular.isNumber('95.55' * 1) == true
angular.isNumber('bla' * 1) == true
angular.isNumber(NaN) == true

I need something to see if a string is a number (when it actually is) and
won't let me do that unless I multiply by 1, but if I do that then it will always be true. Also
is not a number (by definition) and so should return false.

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download