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

2 Answers

0 votes
function checkFloatOrInteger(n: any) {
	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('typescript');




/*
run:

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

*/

 



answered Jan 28, 2022 by avibootz
0 votes
function isInt(n: number) {
    return Number(n) === n && n % 1 === 0;
}
 
function isFloat(n : number) {
    return Number(n) === n && n % 1 !== 0;
}
 
console.log(isInt(55));
console.log(isInt(9.35));
 
console.log(isFloat(2.986));
console.log(isFloat(7));

console.log(isInt(9.35) || isFloat(7.2));
 
 
 
 
/*
run:
 
true
false
true
false
true 
 
*/

 



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