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

前端 未结 30 2576
栀梦
栀梦 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:42

    Trying some of the answers here I ended up writing this solution. This works also with numbers inside a string.

    function isInt(number) {
        if(!/^["|']{0,1}[-]{0,1}\d{0,}(\.{0,1}\d+)["|']{0,1}$/.test(number)) return false;
        return !(number - parseInt(number));
    }
    
    function isFloat(number) {
        if(!/^["|']{0,1}[-]{0,1}\d{0,}(\.{0,1}\d+)["|']{0,1}$/.test(number)) return false;
        return number - parseInt(number) ? true : false;
    }
    

        var tests = {
            'integer' : 1,
            'float' : 1.1,
            'integerInString' : '5',
            'floatInString' : '5.5',
            'negativeInt' : -345,
            'negativeFloat' : -34.98,
            'negativeIntString' : '-45',
            'negativeFloatString' : '-23.09',
            'notValidFalse' : false,
            'notValidTrue' : true,
            'notValidString' : '45lorem',
            'notValidStringFloat' : '4.5lorem',
            'notValidNan' : NaN,
            'notValidObj' : {},
            'notValidArr' : [1,2],
        };
    
        function isInt(number) {
            if(!/^["|']{0,1}[-]{0,1}\d{0,}(\.{0,1}\d+)["|']{0,1}$/.test(number)) return false;
            return !(number - parseInt(number));
        }
        
        function isFloat(number) {
            if(!/^["|']{0,1}[-]{0,1}\d{0,}(\.{0,1}\d+)["|']{0,1}$/.test(number)) return false;
            return number - parseInt(number) ? true : false;
        }
    
        function testFunctions(obj) {
            var keys = Object.keys(obj);
            var values = Object.values(obj);
    
            values.forEach(function(element, index){
                console.log(`Is ${keys[index]} (${element}) var an integer? ${isInt(element)}`);
                console.log(`Is ${keys[index]} (${element}) var a float? ${isFloat(element)}`);
            });
        }
    
        testFunctions(tests);

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

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

    For those curious, using Benchmark.js I tested the most up-voted answers (and the one posted today) on this post, here are my results:

    var n = -10.4375892034758293405790;
    var suite = new Benchmark.Suite;
    suite
        // kennebec
        .add('0', function() {
            return n % 1 == 0;
        })
        // kennebec
        .add('1', function() {
            return typeof n === 'number' && n % 1 == 0;
        })
        // kennebec
        .add('2', function() {
            return typeof n === 'number' && parseFloat(n) == parseInt(n, 10) && !isNaN(n);
        })
    
        // Axle
        .add('3', function() {
            return n.toString().indexOf('.') === -1;
        })
    
        // Dagg Nabbit
        .add('4', function() {
            return n === +n && n === (n|0);
        })
    
        // warfares
        .add('5', function() {
            return parseInt(n) === n;
        })
    
        // Marcio Simao
        .add('6', function() {
            return /^-?[0-9]+$/.test(n.toString());
        })
    
        // Tal Liron
        .add('7', function() {
            if ((undefined === n) || (null === n)) {
                return false;
            }
            if (typeof n == 'number') {
                return true;
            }
            return !isNaN(n - 0);
        });
    
    // Define logs and Run
    suite.on('cycle', function(event) {
        console.log(String(event.target));
    }).on('complete', function() {
        console.log('Fastest is ' + this.filter('fastest').pluck('name'));
    }).run({ 'async': true });
    

    0 x 12,832,357 ops/sec ±0.65% (90 runs sampled)
    1 x 12,916,439 ops/sec ±0.62% (95 runs sampled)
    2 x 2,776,583 ops/sec ±0.93% (92 runs sampled)
    3 x 10,345,379 ops/sec ±0.49% (97 runs sampled)
    4 x 53,766,106 ops/sec ±0.66% (93 runs sampled)
    5 x 26,514,109 ops/sec ±2.72% (93 runs sampled)
    6 x 10,146,270 ops/sec ±2.54% (90 runs sampled)
    7 x 60,353,419 ops/sec ±0.35% (97 runs sampled)
    
    Fastest is 7 Tal Liron
    
    0 讨论(0)
  • 2020-11-22 00:47

    In java script all the numbers are internally 64 bit floating point, same as double in java. There are no diffrent types in javascript, all are represented by type number. Hence you wil l not be able make a instanceof check. However u can use the above solutions given to find out if it is a fractional number. designers of java script felt with a single type they can avoid numerous type cast errors.

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

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

    There is a method called Number.isInteger() which is currently implemented in everything but IE. MDN also provides a polyfill for other browsers:

    Number.isInteger = Number.isInteger || function(value) {
      return typeof value === 'number' && 
        isFinite(value) && 
        Math.floor(value) === value;
    };
    

    However, for most uses cases, you are better off using Number.isSafeInteger which also checks if the value is so high/low that any decimal places would have been lost anyway. MDN has a polyfil for this as well. (You also need the isInteger pollyfill above.)

    if (!Number.MAX_SAFE_INTEGER) {
        Number.MAX_SAFE_INTEGER = 9007199254740991; // Math.pow(2, 53) - 1;
    }
    Number.isSafeInteger = Number.isSafeInteger || function (value) {
       return Number.isInteger(value) && Math.abs(value) <= Number.MAX_SAFE_INTEGER;
    };
    
    0 讨论(0)
提交回复
热议问题