There's a much easier way to check if a number is a float. Just compare the floored value against the original value. If they're the same, it's an integer.
function isFloat(n) {
return Math.floor(n) !== n;
}
console.log(isFloat(1));
console.log(isFloat(1.2));
console.log(isFloat(12));
console.log(isFloat(12.4));
This will work if, and only if, you only use it on numbers. You can perform an additional check if you're worried about someone passing in non-numbers.
function isFloat(n) {
return typeof n === 'number' && Math.floor(n) !== n;
}
Or you can simplify this even further by using Number.isInteger
, provided you're running an environment that supports it.
function isFloat(n) {
return typeof n === 'number' && !Number.isInteger(n);
}
console.log(isFloat(1));
console.log(isFloat(1.2));
console.log(isFloat(12));
console.log(isFloat(12.4));
console.log(isFloat('a'));