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

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

当前回答

正如其他人提到的,你在JS中只有双打。那么,如何定义一个整数?只需检查舍入数字是否等于自身:

function isInteger(f) {
    return typeof(f)==="number" && Math.round(f) == f;
}
function isFloat(f) { return typeof(f)==="number" && !isInteger(f); }

其他回答

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

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

试试这个

let n;
return (n = value % 1) !== 0 && !isNaN(n);

当返回值为false时,表示输入值为浮点数或浮点数字符串,否则输入值为整数numref或整数字符串。

基本上,它需要检查精度值是否不等于零。

另一个是检查正确的字符串编号。

这个解决方案对我有效。

<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(value) {

    var er = /^-?[0-9]+$/;

    return er.test(value);
}

或者,您也可以根据需要使用以下功能。它们由PHPJS项目开发。

is_int()=>检查变量类型是否为整数,其内容是否为整数

is_float()=>检查变量类型是否为float,其内容是否为floate

ctype_digit()=>检查变量类型是否为字符串,以及其内容是否只有小数位数

更新1

现在它也检查负数,感谢@ChrisBartley的评论!

我知道已经有30个答案,但一个复杂的方法是这样做:

function isInteger(n) {
    return n.toString().split('.').length === 1;
}

解释:我们首先将n转换为字符串,然后基于点拆分它。如果n是浮点,如4.5,则拆分将返回数组['4','5']。如果它是像45这样的整数,它将返回['45']。因此,如果数组的长度是1,那么我们知道它是一个数字。

注:如果您想以新的ES6格式(箭头函数)编写此函数:

const isInteger = n => n.toString().split('.').length === 1;