如何发现一个数字是浮点数或整数?

1.25 --> float  
1 --> integer  
0 --> integer  
0.25 --> float

当前回答

对于浮动

var decimal=  /^[-+]?[0-9]+\.[0-9]+$/; 

if (!price.match(decimal)) {
      alert('Please enter valid float');
      return false;
    }

对于整数

var number = /^\d+$/; 

if (!price.match(number)) {
      alert('Please enter valid integer');
      return false;
    }

其他回答

对于整数,我使用这个

function integer_or_null(value) {
    if ((undefined === value) || (null === value)) {
        return null;
    }
    if(value % 1 != 0) {
        return null;
    }
    return value;
}

基于我在这里看到的所有内容,我创建了自己的一组函数来测试我所需要的:

function NumberValidator() {
this.isFloat = function (n) {
    return typeof(n)==="number" && n === +n && Math.round(n) !== n;
};

this.isInteger = function (n) {
    return typeof(n)==="number" && n === +n && Math.round(n) === n;
};

this.isFloatOrInteger = function (n) {
    return this.isFloat(n) || this.isInteger(n);
};

this.isNonZeroFloatOrInteger = function (n) {
    return this.isFloatOrInteger(n) && n > 0;
};

this.isNonZeroInteger = function (n) {
    return this.isInteger(n) && n > 0;
};
}

然而,shime的解决方案更短,检查更少,因此可能是更好的解决方案。

任何小数点为零的浮点数(例如1.0、12.00、0.0)都隐式转换为整数,因此无法检查它们是否为浮点数。

您可以使用Number.isInteger()方法通过对数字进行除法来检查数字是整数还是浮点数,例如:

    function isNumberFloatOrInteger(a, b){
     if(Number.isInteger(a / b)){
      return true;
      }
      else{ return false };
}

注意:isInteger()与internet explorer不兼容。

parseInt(yourNumber)=== parseFloat(yourNumber)