Reputation: 135
So to check if a string is a positive integer, I have done some research and found this solution here by someone: Validate that a string is a positive integer
function isNormalInteger(str) {
return /^\+?(0|[1-9]\d*)$/.test(str);
}
However, I put this into test, and found that numbers with pure 0's on the decimal places does not seem to be working. For example:
15 ===> Works!
15.0 ====> Does not work :(
15.000 ===> Does not work :(
Build upon the existing method, how could I allow pure-0's on the decimal places and make them all work? Please note 15.38 should not work, but 15.00 should.
Upvotes: 1
Views: 389
Reputation: 11
Quick and dirty
function isNormalInteger(str) {
var ival=parseInt(str);
return ival!=NaN && ival>=0 && ival==parseFloat(str);
}
Upvotes: 1
Reputation: 32145
First of all the function should be called isNormalNumber
instead of isNormalInteger
as it accepts decimals, then this is the REgex you need:
function isNormalNumber(str) {
return /^\+*[0-9]\d*(\.0+)?$/.test(str);
}
alert(isNormalNumber("+10.0") + "::" + isNormalNumber("+10.9") + "::" + isNormalNumber("10"));
Returns true::false:true
.
EDIT:
This is an edit to avoid matching leading zeros like in the numbers 001234
and 07878
:
^\+*[1-9]\d*(\.0+)?$|^0(\.0+)?$
Upvotes: 1
Reputation: 785156
No need to use regex here.
function isNormalInteger(str) {
var n = parseInt(str);
return n > 0 && n == +str;
}
Then test it:
isNormalInteger(15)
true
isNormalInteger(15.00)
true
isNormalInteger(15.38)
false
isNormalInteger(-15)
false
isNormalInteger(-15.1)
false
Upvotes: 3