【问题标题】:Check a value is float or int in jquery在jquery中检查一个值是float还是int
【发布时间】:2013-12-01 11:22:26
【问题描述】:

我有以下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。

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

【问题讨论】:

标签: jquery int


【解决方案1】:

使用typeof检查类型,然后value % 1 === 0识别int如下,

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

【讨论】:

  • 请注意,即使值的类型是“数字”,它仍然可以是数字,因为 NaN 的类型是数字
  • @AndersM。然后使用 IsNumeric。
  • 如果一个数字在小数点后为零,例如。 10.0 将被视为 float 或 int ?
【解决方案2】:

你可以使用正则表达式

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

【讨论】:

  • 完美! @Mahmoude Elghandour
【解决方案3】:

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

// 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 类型。

【讨论】:

    【解决方案4】:

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

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

    【讨论】:

    • k 为了检查它是否是一个整数,也许我们也可以在 jquery 中使用默认的.isNumeric,所以现在需要找到它是否是一个浮点数,还有它有任何默认方法,如.isNumeric 在 jquery 中?
    • @shivakrishna:- 是的,Jquery 中有一个函数 .isNumeric。 api.jquery.com/jQuery.isNumeric
    • @rahuli 的意思是问,是否也有用于寻找浮动的?
    • 你可以像这样检查浮点数:function isFloat(value) { return value === +value && value !== (value|0); }
    • @shivakrishna:- 当然,试一试!
    【解决方案5】:

    你就这样检查

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

    【讨论】:

    • 考虑到这是 html,你可能会得到字符串值。你可以得到'1.0''str',甚至'',这将无法正确识别。
    猜你喜欢
    • 2011-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-03
    • 1970-01-01
    • 2021-10-19
    相关资源
    最近更新 更多