how to find if a number is float or integer?
1.25 --> float
1 --> integer
0 --> integer
0.25 --> integer
how to find if a number is float or integer?
1.25 --> float
1 --> integer
0 --> integer
0.25 --> integer
Try this.
function isFloat (n) {
return n===+n && n!==(n|0);
}
function isInteger (n) {
return n===+n && n===(n|0);
}
As others mentioned, you only have doubles in JS. So how do you define a number being an integer? Just check if the rounded number is equal to itself:
function isInteger(f) {
return typeof(f)==="number" && Math.round(f) == f;
}
function isFloat(f) { return typeof(f)==="number" && !isInteger(f); }
It really depends on what you want to achieve. If you want to "emulate" strongly typed languages then I suggest you not trying. As others mentioned all numbers have the same representation (the same type).
Using something like Claudiu provided:
isInteger( 1.0 ) -> true
which looks fine for common sense, but in something like C you would get false
check a remainder when dividing by 1:
function isInt(n){
return n%1==0
}
If you don't know that the argument is a number-
function isInt(n){
return typeof n== 'number' && n%1==0
}