在jquery中检查值是float还是int

时间:2013-12-01 11:22:26

标签: jquery int

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

   });

});

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

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

5 个答案:

答案 0 :(得分:10)

使用typeof检查类型,然后使用value % 1 === 0将int标识为以下,

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

答案 1 :(得分:3)

您可以使用正则表达式

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'); 
    }

答案 2 :(得分: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
}

请注意,输入字段中的值仍然是字符串,而不是number类型。

答案 3 :(得分:0)

我认为最好的想法就是这样检查,即在除以1时检查余数:

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

答案 4 :(得分:0)

你就这样检查

if (value.toString().indexOf('.') == -1) {
  console.log('i am a integer');
}​ else {
  console.log('i am a float');
}
相关问题