How to check if a number is a float or integer in JavaScript

2 Answers

0 votes
function checkFloatOrInteger(n) {
	if (typeof n == 'number' && !isNaN(n)) {
        if (Number.isInteger(n)) {
            console.log(`${n} is integer`);
        }
        else {
            console.log(`${n} is float`);
        }
    
    } else {
        console.log(`${n} is not a number`);
    }
}


checkFloatOrInteger(3456);
checkFloatOrInteger(3.14);
checkFloatOrInteger(-2.895);
checkFloatOrInteger(NaN);
checkFloatOrInteger('javascript');




/*
run:

"3456 is integer"
"3.14 is float"
"-2.895 is float"
"NaN is not a number"
"javascript is not a number"

*/

 



answered Jan 28, 2022 by avibootz
edited Jan 28, 2022 by avibootz
0 votes
function isInt(n) {
    return Number(n) === n && n % 1 === 0;
}
 
function isFloat(n) {
    return Number(n) === n && n % 1 !== 0;
}
 
console.log(isInt(12));
console.log(isInt(8.35));
 
console.log(isFloat(3.14));
console.log(isFloat(3));

console.log(isInt(8.35) || isFloat(3));
 
 
 
 
/*
run:
 
true
false
true
false
false
 
*/

 



answered Jan 28, 2022 by avibootz
edited Jan 28, 2022 by avibootz

Related questions

...