Here are a few instances where your code may not work as expected:
'0x12'
In this case, the number is parsed as hexadecimal by both Number() and parseInt(), which might not align with what you intended. This can be rectified by passing 10 as the radix into parseInt.
'1.0000000000000001' JavaScript numbers struggle to store enough significant figures to accurately represent this number.
To address these issues, I recommend conducting two separate checks for Numbers and Strings. For Numbers, utilize Math.floor() to see if rounding down alters the number. For Strings, employ a RegExp to ensure the string solely consists of '-' and digits. Consider the following function:
function isint(o) {
if (typeof o === 'number') {
return Math.floor(o) === o;
}
else if (typeof o === 'string' &&
/^-?\d+$/.test(o)) {
var num = Number(o);
return num.toString() === o;
}
return false;
}
Give it a try:
[12, 13, '14', '-1', '0x12', '1.0000000000000001'].forEach(function(x) {
console.log(x + ' isInt = ' + isint(x));
});
The output will be:
12 isInt = true
13 isInt = true
14 isInt = true
-1 isInt = true
0x12 isInt = false
1.0000000000000001 isInt = false