Check a value is float or int in jquery

梦想与她 提交于 2019-12-22 07:51:45

问题


I have the following html field, for which i need to check whether the input value is float or int,

<p class="check_int_float" name="float_int" type="text"></p>


$(document).ready(function(){
   $('.check_int_float').focusout(function(){

       var value  = this.value
       if (value is float or value is int)
          {
           // do something
          }      
       else
          {
           alert('Value must be float or int');   
          }  

   });

});

So how to check whether a value is float or int in jquery.

I need to find/check both cases, whether it is a float, or int, because later if the value was float i will use it for some purpose and similarly for int.


回答1:


use typeof to check the type, then value % 1 === 0 to identify the int as bellow,

if(typeof value === 'number'){
   if(value % 1 === 0){
      // int
   } else{
      // float
   }
} else{
   // not a number
}



回答2:


You can use a regular expression

var float= /^\s*(\+|-)?((\d+(\.\d+)?)|(\.\d+))\s*$/;
var a = $(".check_int_float").val();
if (float.test(a)) {
        // do something
    }
    //if it's NOT valid
    else {
   alert('Value must be float or int'); 
    }



回答3:


You can use a regular expression to determine if the input is satisfying:

// Checks that an input string is a decimal number, with an optional +/- sign   character.
var isDecimal_re = /^\s*(\+|-)?((\d+(\.\d+)?)|(\.\d+))\s*$/;

function isDecimal (s) {
    return String(s).search (isDecimal_re) != -1
}

Keep in mind that the value from the input field is still a string and not a number type yet.




回答4:


I think the best idea would be to check like this ie, to check the remainder when dividing by 1:

function isInt(value) {
    return typeof value === 'Num' && parseFloat(value) == parseInt(value, 10) && !isNaN(value);
 } 


来源:https://stackoverflow.com/questions/20311572/check-a-value-is-float-or-int-in-jquery

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!