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

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

    It really doesn't have to be so complicated. The numeric value of an integer's parseFloat() and parseInt() equivalents will be the same. Thus you can do like so:

    function isInt(value){ 
        return (parseFloat(value) == parseInt(value)) && !isNaN(value);
    }
    

    Then

    if (isInt(x)) // do work
    

    This will also allow for string checks and thus is not strict. If want a strong type solution (aka, wont work with strings):

    function is_int(value){ return !isNaN(parseInt(value * 1) }
    

提交回复
热议问题