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

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

    Here are efficient functions that check if the value is a number or can be safely converted to a number:

    function isNumber(value) {
        if ((undefined === value) || (null === value)) {
            return false;
        }
        if (typeof value == 'number') {
            return true;
        }
        return !isNaN(value - 0);
    }
    

    And for integers (would return false if the value is a float):

    function isInteger(value) {
        if ((undefined === value) || (null === value)) {
            return false;
        }
        return value % 1 == 0;
    }
    

    The efficiency here is that parseInt (or parseNumber) are avoided when the value already is a number. Both parsing functions always convert to string first and then attempt to parse that string, which would be a waste if the value already is a number.

    Thank you to the other posts here for providing further ideas for optimization!

提交回复
热议问题