还有什么我可以使用而不是Number.isInteger?

时间:2017-12-12 16:54:22

标签: javascript

Number.isInteger不适用于某些IE浏览器。我是一个控制轮值是否为整数。

var decimalBasePriceKontol = Number.isInteger(BasePrice);

这是我的变数。

我可以用什么方法在所有浏览器上进行此操作。

谢谢,

3 个答案:

答案 0 :(得分:0)

你不会比Mozilla Polyfill好。将其添加到脚本的顶部:

Number.isInteger = Number.isInteger || function(value) {
    return typeof value === 'number' && 
        isFinite(value) && 
        Math.floor(value) === value;
    };

现在,它在做什么?

// This line makes sure that the function isInteger exists. 
// If it doesn't it creates it
Number.isInteger = Number.isInteger || function(value) {
    // This line checks to make sure we're dealing with a number object.
    // After all "cat" is not an integer
    return typeof value === 'number' && 
    // This line makes sure we're not checking Infinity. 
    // Infinity is a number, and if you round it, then it equals itself.
    // which means it would fail our final test.
    isFinite(value) && 
    // If you round, floor, or ceil an integer, the same value will return.
    // if you round, floor, or ceil a float, then it will return an integer.
    Math.floor(value) === value;
}

答案 1 :(得分:0)

注意:仅当值为数字(整数,浮点数,...)时才有效。您也可以查看其他类型。

您可以将其转换为字符串,然后检查是否有.个字符(小数点)。

var decimalBasePriceKontol = BasePrice.toString().indexOf(".")==-1

您也可以替换Number.isInteger :(在第一次使用Number.isInteger之前运行它)

if (!Number.isInteger) { // If Number.isInteger is not defined
    Number.isInteger = function (n) {
        return n.toString().indexOf(".")==-1;
    };
}

答案 2 :(得分:0)

要检查是否为整数,我在IE浏览器中使用了以下方法:

if (!value || !/^\d+$/.test(value)) {
    return false;
 } else { 
  //It's an integer
    return true;
}