Why Is Angular.isNumber() Not Working As Expected?
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 isNaN()? angular.isNumber
Solution 1:
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
Solution 2:
I was working on the same problem and I was trying to work around that edge case. So I created a slightly different approach.
function isStringNumber(str) {
var parsed = parseFloat(str);
var casted = +str;
return parsed === casted && !isNaN(parsed) && !isNaN(casted);
}
Solution 3:
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
Post a Comment for "Why Is Angular.isNumber() Not Working As Expected?"