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

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

当前回答

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

函数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]));}

其他回答

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

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

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

我知道已经有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;

在java脚本中,所有数字都是内部64位浮点,与java中的double相同。javascript中没有不同的类型,所有类型都由类型号表示。因此,您将无法进行检查实例。然而,你可以使用上面给出的解来确定它是否是一个分数。java脚本的设计者认为,只要使用一种类型,就可以避免大量的类型转换错误。

以下是检查值是否为数字或是否可以安全地转换为数字的有效函数:

function isNumber(value) {
    if ((undefined === value) || (null === value)) {
        return false;
    }
    if (typeof value == 'number') {
        return true;
    }
    return !isNaN(value - 0);
}

对于整数(如果值是浮点,则返回false):

function isInteger(value) {
    if ((undefined === value) || (null === value)) {
        return false;
    }
    return value % 1 == 0;
}

这里的效率是,当值已经是数字时,可以避免parseInt(或parseNumber)。这两个解析函数总是先转换为字符串,然后尝试解析该字符串,如果值已经是数字,这将是一种浪费。

感谢这里的其他帖子为优化提供了进一步的想法!

function int(a) {
  return a - a === 0 && a.toString(32).indexOf('.') === -1
}

function float(a) {
  return a - a === 0 && a.toString(32).indexOf('.') !== -1
}

如果要排除字符串,可以添加类型a==“number”。