A few examples that break with your code:
'0x12'
This breaks down because Number() and parseInt() both try to do JavaScript style parsing of the numbers - in this case parsing the number as hex. (But maybe you are ok with this). A simple change to pass 10 as the radix into parseInt would fix this part of your code.
'1.0000000000000001' This breaks down because JavaScript numbers can not store enough significant figures to represent this number.
I'd suggest doing two checks, one for Numbers and one for Strings. For Numbers, you can take the floor() to see if the number changes when rounding down. For the Strings, use a RegExp to check that the string only contains a '-' and digits. Something like:
function isint(o) {
if (typeof o === 'number') {
// o is an int if rounding down doesn't change it.
return Math.floor(o) === o;
}
else if (typeof o === 'string' &&
/^-?\d+$/.test(o)) { // match '-' (optional) followed by 1 or more digits
// o is an int if parsing the string, and toString()ing it gets you the same value
var num = Number(o);
return num.toString() === o;
}
return false;
}
Try it:
[12, 13, '14', '-1', '0x12', '1.0000000000000001'].forEach(function(x) {
console.log(x + ' isInt = ' + isint(x));
});
Prints:
12 isInt = true
13 isInt = true
14 isInt = true
-1 isInt = true
0x12 isInt = false
1.0000000000000001 isInt = false