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

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

当前回答

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

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

其他回答

const integerCheck = (num) => {
        const isInt = (n) => Number(n) === n && n % 1 === 0
        const isFloat = (n) => Number(n) === n && n % 1 !== 0
        return (isInt(num) || !isFloat(num))        
}
console.log( integerCheck('23.3') );

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

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

function isInt(n) 
{
    return n != "" && !isNaN(n) && Math.round(n) == n;
}
function isFloat(n){
    return n != "" && !isNaN(n) && Math.round(n) != n;
}

适用于所有情况。

这里有Number.isInteger(数字)来检查。在Internet Explorer中不工作,但该浏览器不再使用。如果您需要像“90”这样的字符串作为整数(这不是问题),请尝试Number.isInteger(Number(Number))。“官方”isInteger将9.0视为整数,请参见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number.看起来大多数答案对旧版浏览器都是正确的,但现代浏览器已经进步,实际上支持浮点整数检查。

可以使用简单的正则表达式:

function isInt(value) {

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

    return er.test(value);
}

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

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

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

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

更新1

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