How to check if a number is a float or integer in Node.js

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('node.js');




/*
run:

3456 is integer
3.14 is float
-2.895 is float
NaN is not a number
node.js is not a number

*/

 



answered 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(98));
console.log(isInt(1.256));
 
console.log(isFloat(7.9784));
console.log(isFloat(6));

console.log(isInt(1.256) || isFloat(6));
 
 
 
 
 
/*
run:
 
true
false
true
false
false
 
*/

 



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