0

可能重复:
如何检查数字是浮点数还是整数?

检查变量是否为整数的最佳方法是什么?

在 Python 中,您可以执行以下操作:

 if type(x) == int

JS 中是否有同样优雅的等价物?

4

4 回答 4

2

我没有测试,但我建议:

if (Math.round(x) == x) {
    // it's an integer
}

简单的JS 小提琴

于 2012-11-18T23:07:59.630 回答
0

整数的 parseFloat() 和 parseInt() 等效项的数值将相同。因此你可以这样做:

function isInt(value){ 
    return (parseFloat(value) == parseInt(value)) && !isNaN(value);
}

然后

if (isInt(x)) // do work
于 2012-11-18T23:16:46.763 回答
0

Javascript 提供 typeof

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/typeof

   // Numbers
   typeof 37 === 'number';
   typeof 3.14 === 'number';
   typeof Math.LN2 === 'number';
   typeof Infinity === 'number';
   typeof NaN === 'number'; // Despite being "Not-A-Number"
   typeof Number(1) === 'number'; // but never use this form!
于 2012-11-18T23:10:11.803 回答
0

使用isNaN(不是数字 - 但要注意逻辑是否定的)并与 parseInt 结合使用:

function is_int(x)
{
    return (!isNaN(x) && parseInt(x) == x)
}

正如这里所建议的,以下内容也可以:

function isInt(n) {
   return n % 1 === 0;
}
于 2012-11-18T23:07:36.247 回答