How do I check that a number is float or integer?

2018-12-31 03:48发布

How to find that a number is float or integer?

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

30条回答
千与千寻千般痛.
2楼-- · 2018-12-31 04:19

There is a method called Number.isInteger() which is currently implemented only in latest Firefox and is still a part of EcmaScript 6 proposal. However MDN provides a polyfill for the other browsers, which matches the one specified in ECMA harmony:

if (!Number.isInteger) {
  Number.isInteger = function isInteger (nVal) {
    return typeof nVal === "number" && isFinite(nVal) && nVal > -9007199254740992 && nVal < 9007199254740992 && Math.floor(nVal) === nVal;
  };
}
查看更多
浪荡孟婆
3楼-- · 2018-12-31 04:19

Here's what I use for integers:

Math.ceil(parseFloat(val)) === val

Short, nice :) Works all the time. This is what David Flanagan suggests if I'm not mistaken.

查看更多
还给你的自由
4楼-- · 2018-12-31 04:20

This solution worked for me.

<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>
查看更多
唯独是你
5楼-- · 2018-12-31 04:21
function isInt(n) 
{
    return n != "" && !isNaN(n) && Math.round(n) == n;
}
function isFloat(n){
    return n != "" && !isNaN(n) && Math.round(n) != n;
}

works for all cases.

查看更多
查无此人
6楼-- · 2018-12-31 04:22

As others mentioned, you only have doubles in JS. So how do you define a number being an integer? Just check if the rounded number is equal to itself:

function isInteger(f) {
    return typeof(f)==="number" && Math.round(f) == f;
}
function isFloat(f) { return typeof(f)==="number" && !isInteger(f); }
查看更多
与风俱净
7楼-- · 2018-12-31 04:22
function isInteger(n) {
   return ((typeof n==='number')&&(n%1===0));
}

function isFloat(n) {
   return ((typeof n==='number')&&(n%1!==0));
}

function isNumber(n) {
   return (typeof n==='number');
}
查看更多
登录 后发表回答