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

前端 未结 30 2597
栀梦
栀梦 2020-11-22 00:01

How to find that a number is float or integer?

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


        
相关标签:
30条回答
  • 2020-11-22 00:35

    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;
    }
    
    0 讨论(0)
  • 2020-11-22 00:36
    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.

    0 讨论(0)
  • 2020-11-22 00:36

    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.

    0 讨论(0)
  • 2020-11-22 00:36
    var isInt = function (n) { return n === (n | 0); };
    

    Haven't had a case where this didn't do the job.

    0 讨论(0)
  • 2020-11-22 00:36

    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;   
    }   
    
    0 讨论(0)
  • 2020-11-22 00:37

    Why not something like this:

    var isInt = function(n) { return parseInt(n) === n };
    
    0 讨论(0)
提交回复
热议问题