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

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

当前回答

这个解决方案对我有效。

<html>
<body>
  <form method="post" action="#">
    <input type="text" id="number_id"/>
    <input type="submit" value="send"/>
  </form>
  <p id="message"></p>
  <script>
    var flt=document.getElementById("number_id").value;
    if(isNaN(flt)==false && Number.isInteger(flt)==false)
    {
     document.getElementById("message").innerHTML="the number_id is a float ";
    }
   else 
   {
     document.getElementById("message").innerHTML="the number_id is a Integer";
   }
  </script>
</body>
</html>

其他回答

我们可以通过isInteger函数进行检查。ie number将返回true,float返回false

console.log(Number.isIInteger(2)),<BR>将返回true

console.log(Number.isInteger(2.5))将返回false

比较floor()结果与ceil()结果不同。

const isFloat = v => Math.floor(v) !== Math.ceil(v);
> isFloat(1)
= false

> isFloat(1.1)
= true

> isFloat(42)
= false

> isFloat(84.42)
= true

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

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的解决方案更短,检查更少,因此可能是更好的解决方案。

对于浮动

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

我需要检查一个输入值,如果它是整数或浮点值,为此我想出了以下方法:

函数isInteger(x){var整数=parseInt(x,10);如果(!isNaN(整数)&&!isFloat(x)){返回true;}return false;}函数isFloat(x){var f=parseFloat(x);var floor=数学楼层(f);var分数=f-地板;如果(分数>0){返回true;}return false;}var案例=["1","1.00","1.01","0.05",“ab1”,“ab1.1”,1.1.00,1.01,0.05,1e+5,"",真的,假,无效的NaN,未定义,];console.log(“isInteger()”);对于(var i=0;i<cases.length;i++){console.log(cases[i],isInteger(cases[i]));}console.log(“\nisFloat()”);对于(var i=0;i<cases.length;i++){console.log(cases[i],isFloat(cases[i]));}