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

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

当前回答

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

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)。这两个解析函数总是先转换为字符串,然后尝试解析该字符串,如果值已经是数字,这将是一种浪费。

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

其他回答

下面的函数防止空字符串、未定义、空值和max/min值范围。Javascript引擎从一开始就应该内置这些函数。:)

享受

function IsInteger(iVal) {
    var iParsedVal; //our internal converted int value


    iParsedVal = parseInt(iVal,10);

    if (isNaN(iParsedVal) || Infinity == iParsedVal || -Infinity == iParsedVal) //sanity check - guard against empty strings and max/min values
        return false;
    else
        return Number(iVal) === (iParsedVal | 0); //the 2nd operand group (intValue | 0), evaluates to true only if the intValue is an integer; so an int type will only return true
}

function IsFloat(fVal) {
    var fParsedVal; //our internal converted float value


    fParsedVal = parseFloat(fVal);

    if (isNaN(fParsedVal) || Infinity == fParsedVal || -Infinity == fParsedVal) //sanity check - guard against empty strings and max/min values
        return false;
    else
        return !!(fVal % 1); //true only if there is a fractional value after the mod op; the !! returns the opposite value of the op which reflects the function's return value
}

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

浮动验证条件:

if (lnk.value == +lnk.value && lnk.value != (lnk.value | 0)) 

整数验证条件:

if (lnk.value == +lnk.value && lnk.value == (lnk.value | 0)) 

希望这可能会有所帮助。

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') );
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');
}