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

前端 未结 30 2594
栀梦
栀梦 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);

提交回复
热议问题