Sometimes, there's the need to verify if a given number is an integer or a decimal. Since JavaScript doesn't distinguish between both, I've made an extremelly basic function.
function isInteger(num){
var numCopy = parseFloat(num);
return !isNaN(numCopy) && numCopy == numCopy.toFixed();
}
As you can see, it relies on checking if the number without decimals is the same as the parsed value. I'm not so confident about this.
Notice that this may return true
for some scientific notation values.
Examples of results:
1.0
:true
(JavaScript treats<n>.0
as an integer)1e3
:true
1.2345e2
:false
(equivalent to 123.45)1.2345e5
:true
(equivalent to 123450)1e200
:true
(equivalent toInfinity
)
Is there any more reliable way of checking? The results seem to be consistent with the expected results. Regular expressions are an option but they are clunky.