If we consider a JavaScript integer to be a value of maximum 4294967295
(i.e. Math.pow(2,32)-1
), then the following short solution will perfectly work:
function isPositiveInteger(n) {
return n >>> 0 === parseFloat(n);
}
DESCRIPTION:
123.45 >>> 0 === 123
-1 >>> 0 === 4294967295
MAX_INT
1e10 >>> 0 === 1410065408
1e7 >>> 0 === 10000000
parseFloat
does correct parsing of string numbers (setting NaN
for non numeric strings)TESTS:
"0" : true
"23" : true
"-10" : false
"10.30" : false
"-40.1" : false
"string" : false
"1234567890" : true
"129000098131766699.1" : false
"-1e7" : false
"1e7" : true
"1e10" : false
"1edf" : false
" " : false
"" : false
DEMO: http://jsfiddle.net/5UCy4/37/
Another way is good for all numeric values which are valid up to Number.MAX_VALUE
, i.e. to about 1.7976931348623157e+308
:
function isPositiveInteger(n) {
return 0 === n % (!isNaN(parseFloat(n)) && 0 <= ~~n);
}
DESCRIPTION:
!isNaN(parseFloat(n))
is used to filter pure string values, e.g. ""
, " "
, "string"
;0 <= ~~n
filters negative and large non-integer values, e.g. "-40.1"
, "129000098131766699"
;(!isNaN(parseFloat(n)) && 0 <= ~~n)
returns true
if value is both numeric and positive;0 === n % (...)
checks if value is non-float -- here (...)
(see 3) is evaluated as 0
in case of false
, and as 1
in case of true
.TESTS:
"0" : true
"23" : true
"-10" : false
"10.30" : false
"-40.1" : false
"string" : false
"1234567890" : true
"129000098131766699.1" : false
"-1e10" : false
"1e10" : true
"1edf" : false
" " : false
"" : false
DEMO: http://jsfiddle.net/5UCy4/14/
The previous version:
function isPositiveInteger(n) {
return n == "0" || ((n | 0) > 0 && n % 1 == 0);
}