How to find that a number is float
or integer
?
1.25 --> float
1 --> integer
0 --> integer
0.25 --> float
<
For integers I use this
function integer_or_null(value) {
if ((undefined === value) || (null === value)) {
return null;
}
if(value % 1 != 0) {
return null;
}
return value;
}
function isInt(n)
{
return n != "" && !isNaN(n) && Math.round(n) == n;
}
function isFloat(n){
return n != "" && !isNaN(n) && Math.round(n) != n;
}
works for all cases.
Here's what I use for integers:
Math.ceil(parseFloat(val)) === val
Short, nice :) Works all the time. This is what David Flanagan suggests if I'm not mistaken.
var isInt = function (n) { return n === (n | 0); };
Haven't had a case where this didn't do the job.
THIS IS FINAL CODE FOR CHECK BOTH INT AND FLOAT
function isInt(n) {
if(typeof n == 'number' && Math.Round(n) % 1 == 0) {
return true;
} else {
return false;
}
}
OR
function isInt(n) {
return typeof n == 'number' && Math.Round(n) % 1 == 0;
}
Why not something like this:
var isInt = function(n) { return parseInt(n) === n };