在jquery中检查值是float还是int

Shi*_*dla 4 int jquery

我有以下html字段,我需要检查输入值是浮点数还是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');   
          }  

   });

});
Run Code Online (Sandbox Code Playgroud)

那么如何在jquery中检查值是float还是int.

我需要找到/检查这两种情况,无论是浮点数还是int,因为稍后如果值为floati,我会将它用于某种目的,类似地int.

Jan*_*ana 11

使用typeof检查类型,然后value % 1 === 0找出INT为波纹管,

if(typeof value === 'number'){
   if(value % 1 === 0){
      // int
   } else{
      // float
   }
} else{
   // not a number
}
Run Code Online (Sandbox Code Playgroud)

  • 如果一个数字在十进制后为零,例如。10.0 会被认为是 float 还是 int ? (2认同)

Mah*_*our 6

您可以使用正则表达式

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'); 
    }
Run Code Online (Sandbox Code Playgroud)


ret*_*eto 1

您可以使用正则表达式来确定输入是否令人满意:

// 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
}
Run Code Online (Sandbox Code Playgroud)

请记住,输入字段中的值仍然是字符串,而不是类型number