How do I check that a number is float or integer?

2018-12-31 03:48发布

How to find that a number is float or integer?

1.25 --> float  
1 --> integer  
0 --> integer  
0.25 --> float

30条回答
无与为乐者.
2楼-- · 2018-12-31 04:34
function int(a) {
  return a - a === 0 && a.toString(32).indexOf('.') === -1
}

function float(a) {
  return a - a === 0 && a.toString(32).indexOf('.') !== -1
}

You can add typeof a === 'number' if you want to exclude strings.

查看更多
梦寄多情
3楼-- · 2018-12-31 04:35

This maybe isn't as performant as the % answer, which prevents you from having to convert to a string first, but I haven't seen anyone post it yet, so here's another option that should work fine:

function isInteger(num) {
    return num.toString().indexOf('.') === -1;
}
查看更多
流年柔荑漫光年
4楼-- · 2018-12-31 04:36

Here's my code. It checks to make sure it's not an empty string (which will otherwise pass) and then converts it to numeric format. Now, depending on whether you want '1.1' to be equal to 1.1, this may or may not be what you're looking for.

var isFloat = function(n) {
    n = n.length > 0 ? Number(n) : false;
    return (n === parseFloat(n));
};
var isInteger = function(n) {
    n = n.length > 0 ? Number(n) : false;
    return (n === parseInt(n));
};

var isNumeric = function(n){

   if(isInteger(n) || isFloat(n)){
        return true;
   }
   return false;

};
查看更多
路过你的时光
5楼-- · 2018-12-31 04:37
!!(24%1) // false
!!(24.2%1) // true
查看更多
不再属于我。
6楼-- · 2018-12-31 04:38

check for a remainder when dividing by 1:

function isInt(n) {
   return n % 1 === 0;
}

If you don't know that the argument is a number you need two tests:

function isInt(n){
    return Number(n) === n && n % 1 === 0;
}

function isFloat(n){
    return Number(n) === n && n % 1 !== 0;
}
查看更多
步步皆殇っ
7楼-- · 2018-12-31 04:38

Any Float number with a zero decimal part (e.g. 1.0, 12.00, 0.0) are implicitly cast to Integer, so it is not possible to check if they are Float or not.

查看更多
登录 后发表回答