公告
财富商城
积分规则
提问
发文
2018-12-31 03:48发布
皆成旧梦
How to find that a number is float or integer?
float
integer
1.25 --> float 1 --> integer 0 --> integer 0.25 --> float
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:
Number.isInteger()
if (!Number.isInteger) { Number.isInteger = function isInteger (nVal) { return typeof nVal === "number" && isFinite(nVal) && nVal > -9007199254740992 && nVal < 9007199254740992 && Math.floor(nVal) === nVal; }; }
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.
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>
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.
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); }
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'); }
最多设置5个标签!
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:Here's what I use for integers:
Short, nice :) Works all the time. This is what David Flanagan suggests if I'm not mistaken.
This solution worked for me.
works for all cases.
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: