How to find that a number is float
or integer
?
1.25 --> float
1 --> integer
0 --> integer
0.25 --> float
<
Here are efficient functions that check if the value is a number or can be safely converted to a number:
function isNumber(value) {
if ((undefined === value) || (null === value)) {
return false;
}
if (typeof value == 'number') {
return true;
}
return !isNaN(value - 0);
}
And for integers (would return false if the value is a float):
function isInteger(value) {
if ((undefined === value) || (null === value)) {
return false;
}
return value % 1 == 0;
}
The efficiency here is that parseInt (or parseNumber) are avoided when the value already is a number. Both parsing functions always convert to string first and then attempt to parse that string, which would be a waste if the value already is a number.
Thank you to the other posts here for providing further ideas for optimization!