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

前端 未结 30 2595
栀梦
栀梦 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) }
    
    0 讨论(0)
  • 2020-11-22 00:31

    You can use a simple regular expression:

    function isInt(value) {
    
        var er = /^-?[0-9]+$/;
    
        return er.test(value);
    }
    

    Or you can use the below functions too, according your needs. They are developed by the PHPJS Project.

    is_int() => Check if variable type is integer and if its content is integer

    is_float() => Check if variable type is float and if its content is float

    ctype_digit() => Check if variable type is string and if its content has only decimal digits

    Update 1

    Now it checks negative numbers too, thanks for @ChrisBartley comment!

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

    This solution worked for me.

    <html>
    <body>
      <form method="post" action="#">
        <input type="text" id="number_id"/>
        <input type="submit" value="send"/>
      </form>
      <p id="message"></p>
      <script>
        var flt=document.getElementById("number_id").value;
        if(isNaN(flt)==false && Number.isInteger(flt)==false)
        {
         document.getElementById("message").innerHTML="the number_id is a float ";
        }
       else 
       {
         document.getElementById("message").innerHTML="the number_id is a Integer";
       }
      </script>
    </body>
    </html>
    
    0 讨论(0)
  • 2020-11-22 00:32

    Condtion for floating validation :

    if (lnk.value == +lnk.value && lnk.value != (lnk.value | 0)) 
    

    Condtion for Integer validation :

    if (lnk.value == +lnk.value && lnk.value == (lnk.value | 0)) 
    

    Hope this might be helpful.

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

    How about this one?

    isFloat(num) {
        return typeof num === "number" && !Number.isInteger(num);
    }
    
    0 讨论(0)
  • 2020-11-22 00:33

    Any Float number with a zero decimal part (e.g. 1.0, 12.00, 0.0) are implicitly cast to Integer, so it is not possible to check if they are Float or not.

    0 讨论(0)
提交回复
热议问题