如何检查一个数字是浮点数还是整数?

时间:2021-09-13 11:17:41

How to find that a number is float or integer?

如何找到一个数字是浮点数还是整数?

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

39 个解决方案

#1


1063  

check for a remainder when dividing by 1:

除1时检查余数:

function isInt(n) {
   return n % 1 === 0;
}

If you don't know that the argument is a number you need two tests:

如果你不知道参数是一个数字,你需要两个测试:

function isInt(n){
    return Number(n) === n && n % 1 === 0;
}

function isFloat(n){
    return Number(n) === n && n % 1 !== 0;
}

#2


142  

Try these functions to test whether a value is a number primitive value that has no fractional part and is within the size limits of what can be represented as an exact integer.

尝试使用这些函数来测试一个值是否是一个没有小数部分的数字原语值,并且是否在可以表示为精确整数的大小范围内。

function isFloat(n) {
    return n === +n && n !== (n|0);
}

function isInteger(n) {
    return n === +n && n === (n|0);
}

#3


81  

Why not something like this:

为什么不像这样:

var isInt = function(n) { return parseInt(n) === n };

#4


48  

There is a method called Number.isInteger() which is currently implemented only in latest Firefox and is still a part of EcmaScript 6 proposal. However MDN provides a polyfill for the other browsers, which matches the one specified in ECMA harmony:

有一个方法叫做Number.isInteger(),它目前只在最新的Firefox中实现,仍然是EcmaScript 6提案的一部分。但是MDN为其他浏览器提供了一个polyfill,它与ECMA harmony中指定的浏览器匹配:

if (!Number.isInteger) {
  Number.isInteger = function isInteger (nVal) {
    return typeof nVal === "number" && isFinite(nVal) && nVal > -9007199254740992 && nVal < 9007199254740992 && Math.floor(nVal) === nVal;
  };
}

#5


33  

You can use a simple regular expression:

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

function isInt(value) {

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

    return er.test(value);
}

Or you can use the below functions too, according your needs. They are developed by the PHPJS Project.

也可以根据需要使用下面的函数。它们是由PHPJS项目开发的。

is_int() => Check if variable type is integer and if its content is integer

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

is_float() => Check if variable type is float and if its content is float

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

ctype_digit() => Check if variable type is string and if its content has only decimal digits

ctype_digit() =>检查变量类型是否是字符串,如果它的内容只有小数位数。

Update 1

更新1

Now it checks negative numbers too, thanks for @ChrisBartley comment!

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

#6


17  

Here are efficient functions that check if the value is a number or can be safely converted to a number:

这里有一些有效的函数,可以检查值是一个数字还是可以安全地转换为一个数字:

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

And for integers (would return false if the value is a float):

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

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

The efficiency here is that parseInt (or parseNumber) are avoided when the value already is a number. Both parsing functions always convert to string first and then attempt to parse that string, which would be a waste if the value already is a number.

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

Thank you to the other posts here for providing further ideas for optimization!

感谢这里的其他帖子为优化提供了更多的思路!

#7


11  

function isInteger(x) { return typeof x === "number" && isFinite(x) && Math.floor(x) === x; }
function isFloat(x) { return !!(x % 1); }

// give it a spin

isInteger(1.0);        // true
isFloat(1.0);          // false
isFloat(1.2);          // true
isInteger(1.2);        // false
isFloat(1);            // false
isInteger(1);          // true    
isFloat(2e+2);         // false
isInteger(2e+2);       // true
isFloat('1');          // false
isInteger('1');        // false
isFloat(NaN);          // false
isInteger(NaN);        // false
isFloat(null);         // false
isInteger(null);       // false
isFloat(undefined);    // false
isInteger(undefined);  // false

#8


9  

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

works for all cases.

适用于所有情况。

#9


6  

As others mentioned, you only have doubles in JS. So how do you define a number being an integer? Just check if the rounded number is equal to itself:

正如其他人提到的,在JS中只有替身。那么如何定义一个数字为整数呢?只需检查整数是否等于它本身:

function isInteger(f) {
    return typeof(f)==="number" && Math.round(f) == f;
}
function isFloat(f) { return typeof(f)==="number" && !isInteger(f); }

#10


6  

Here's what I use for integers:

这是我对整数的用法:

Math.ceil(parseFloat(val)) === val

Short, nice :) Works all the time. This is what David Flanagan suggests if I'm not mistaken.

短小的,漂亮的:)一直有效。如果我没弄错的话,这就是大卫·弗拉纳根的建议。

#11


5  

Any Float number with a zero decimal part (e.g. 1.0, 12.00, 0.0) are implicitly cast to Integer, so it is not possible to check if they are Float or not.

任何带有零位小数部分(如1.0、12.00、0.0)的浮点数都被隐式地转换为整数,因此不可能检查它们是否为浮点数。

#12


4  

!!(24%1) // false
!!(24.2%1) // true

#13


4  

var isInt = function (n) { return n === (n | 0); };

Haven't had a case where this didn't do the job.

还没有这样的例子。

#14


3  

It really depends on what you want to achieve. If you want to "emulate" strongly typed languages then I suggest you not trying. As others mentioned all numbers have the same representation (the same type).

这真的取决于你想要实现什么。如果您想要“模仿”强类型语言,那么我建议您不要尝试。正如其他人所提到的,所有数字都有相同的表示形式(相同的类型)。

Using something like Claudiu provided:

使用类似克劳迪斯提供的:

isInteger( 1.0 ) -> true

isInteger(1.0) -> true

which looks fine for common sense, but in something like C you would get false

这看起来很符合常识,但是像C,你会得到错误?

#15


3  

It's simple as:

很简单:

if( n === parseInt(n) ) ...

Try this in console:

在控制台试试这个:

x=1;
x===parseInt(x); // true
x="1";
x===parseInt(x); // false
x=1.1;
x===parseInt(x); // false, obviously

// BUT!

x=1.0;
x===parseInt(x); // true, because 1.0 is NOT a float!

This confuses a lot of people. Whenever something is .0, it's not a float anymore. It's an integer. Or you can just call it "a numeric thing" for there is no strict distinction like back then in C. Good old times.

这让很多人感到困惑。当一个东西是。0时,它就不再是一个浮点数了。它是一个整数。或者你可以叫它“一个数字的东西”,因为没有严格的区别,就像在c。

So basically, all you can do is check for integer accepting the fact that 1.000 is an integer.

基本上,你能做的就是检查整数接受1。000是整数的事实。

Interesting side note

有趣的边注

There was a comment about huge numbers. Huge numbers mean NO problem for this approach; whenever parseInt is unable to handle the number (for it's too big) it will return something else than the actual value so the test will return FALSE. This is a good thing because if you consider something a "number" you normally expect JS to be able to calculate with it - so yes, numbers are limited and parseInt will take this into consideration, to put it this way.

有一个关于巨大数字的评论。庞大的数字意味着这种方法没有问题;当parseInt无法处理这个数字(因为它太大了)时,它将返回一些其他的东西,而不是实际的值,因此测试将返回FALSE。这是一件好事,因为如果你考虑一个“数字”,你通常希望JS能够用它来计算——是的,数字是有限的,parseInt会考虑这个,这样说。

Try this:

试试这个:

<script>

var a = 99999999999999999999;
var b = 999999999999999999999; // just one more 9 will kill the show!
var aIsInteger = (a===parseInt(a))?"a is ok":"a fails";
var bIsInteger = (b===parseInt(b))?"b is ok":"b fails";
alert(aIsInteger+"; "+bIsInteger);

</script>

In my browser (IE8) this returns "a is ok; b fails" which is exactly because of the huge number in b. The limit may vary but I guess 20 digits "ought to be enough for anybody", to quote a classical :)

在我的浏览器(IE8)中,这返回“a是ok的;b不及格“这正是因为b里面有很多数字。限制可能会变化,但我猜20位数字“应该对任何人都足够了”,引用一句经典的话:)

#16


2  

THIS IS FINAL CODE FOR CHECK BOTH INT AND FLOAT

这是检查INT和FLOAT的最终代码

function isInt(n) { 
   if(typeof n == 'number' && Math.Round(n) % 1 == 0) {
       return true;
   } else {
       return false;
   }
} 

OR

function isInt(n) {   
   return typeof n == 'number' && Math.Round(n) % 1 == 0;   
}   

#17


2  

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

#18


2  

I wrote function which accepts strings (if somebody will need)

我写了一个接受字符串的函数(如果有人需要的话)

function isInt(x) {
    return !isNaN(x) && eval(x).toString().length == parseInt(eval(x)).toString().length
}

function isFloat(x) {
    return !isNaN(x) && !isInt(eval(x)) && x.toString().length > 0
}

example ouptuts:

示例ouptuts:

console.log(isFloat('0.2'))  // true
console.log(isFloat(0.2))    // true
console.log(isFloat('.2'))   // true
console.log(isFloat('-.2'))  // true
console.log(isFloat(-'.2'))  // true
console.log(isFloat(-.2))    // true
console.log(isFloat('u.2'))  // false
console.log(isFloat('2'))    // false
console.log(isFloat('0.2u')) // false

console.log(isInt('187'))  // true
console.log(isInt(187))    // true
console.log(isInt('1.2'))  // false
console.log(isInt('-2'))   // true
console.log(isInt(-'1'))   // true
console.log(isInt('10e1')) // true
console.log(isInt(10e1))   // true

#19


1  

For integers I use this

对于整数,我用这个

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

#20


1  

It really doesn't have to be so complicated. The numeric value of an integer's parseFloat() and parseInt() equivalents will be the same. Thus you can do like so:

真的不需要这么复杂。整数的parseFloat()和parseInt()等价物的数值是相同的。因此你可以这样做:

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

Then

然后

if (isInt(x)) // do work

This will also allow for string checks and thus is not strict. If want a strong type solution (aka, wont work with strings):

这也将允许字符串检查,因此不严格。如果想要强类型的解决方案(比如,不能使用字符串):

function is_int(value){ return !isNaN(parseInt(value * 1) }

#21


1  

In java script all the numbers are internally 64 bit floating point, same as double in java. There are no diffrent types in javascript, all are represented by type number. Hence you wil l not be able make a instanceof check. However u can use the above solutions given to find out if it is a fractional number. designers of java script felt with a single type they can avoid numerous type cast errors.

在java脚本中,所有数字在内部都是64位浮点数,与java中的双精度浮点数相同。javascript中没有不同的类型,所有类型都用类型号表示。因此你就不能做一个instanceof检查。但是你可以使用上面给出的解来确定它是否是小数。java脚本的设计人员感觉只有一种类型,他们可以避免许多类型转换错误。

#22


1  

This maybe isn't as performant as the % answer, which prevents you from having to convert to a string first, but I haven't seen anyone post it yet, so here's another option that should work fine:

这可能不像%答案那样的性能,它阻止您首先转换成字符串,但是我还没有看到任何人发布它,所以这里有另外一个选项应该可以正常工作:

function isInteger(num) {
    return num.toString().indexOf('.') === -1;
}

#23


1  

Here's my code. It checks to make sure it's not an empty string (which will otherwise pass) and then converts it to numeric format. Now, depending on whether you want '1.1' to be equal to 1.1, this may or may not be what you're looking for.

这是我的代码。它检查以确保它不是一个空字符串(否则会通过),然后将其转换为数字格式。现在,根据你想要1.1是否等于1。1,这可能是你想要的,也可能不是。

var isFloat = function(n) {
    n = n.length > 0 ? Number(n) : false;
    return (n === parseFloat(n));
};
var isInteger = function(n) {
    n = n.length > 0 ? Number(n) : false;
    return (n === parseInt(n));
};

var isNumeric = function(n){

   if(isInteger(n) || isFloat(n)){
        return true;
   }
   return false;

};

#24


1  

I like this little function, which will return true for both positive and negative integers:

我喜欢这个小函数,它对于正整数和负整数都是成立的:

function isInt(val) {
    return ["string","number"].indexOf(typeof(val)) > -1 && val !== '' && !isNaN(val+".0");
}

This works because 1 or "1" becomes "1.0", which isNaN() returns false on (which we then negate and return), but 1.0 or "1.0" becomes "1.0.0", while "string" becomes "string.0", neither of which are numbers, so isNaN() returns false (and, again, gets negated).

这是因为1或“1”变成了“1.0”,isNaN()返回false(然后我们将其否定并返回),而1.0或“1.0”变成了“1.0.0”,而“string”变成了“string”。0",它们都不是数字,所以isNaN()返回false(并且,同样,被否定)。

If you only want positive integers, there's this variant:

如果你只想要正整数,有这个变量:

function isPositiveInt(val) {
    return ["string","number"].indexOf(typeof(val)) > -1 && val !== '' && !isNaN("0"+val);
}

or, for negative integers:

或者,负整数:

function isNegativeInt(val) {
    return `["string","number"].indexOf(typeof(val)) > -1` && val !== '' && isNaN("0"+val);
}

isPositiveInt() works by moving the concatenated numeric string ahead of the value to be tested. For example, isPositiveInt(1) results in isNaN() evaluating "01", which evaluates false. Meanwhile, isPositiveInt(-1) results in isNaN() evaluating "0-1", which evaluates true. We negate the return value and that gives us what we want. isNegativeInt() works similarly, but without negating the return value of isNaN().

isPositiveInt()的工作方式是将连接的数字字符串移动到要测试的值之前。例如,isPositiveInt(1)导致isNaN()计算“01”,它计算false。与此同时,isPositiveInt(-1)结果isNaN()对“0-1”进行评估,该评估为true。我们减去返回值,得到我们想要的。isNegativeInt()的工作原理类似,但不会否定isNaN()的返回值。

Edit:

编辑:

My original implementation would also return true on arrays and empty strings. This implementation doe not have that defect. It also has the benefit of returning early if val is not a string or number, or if it's an empty string, making it faster in these cases. You can further modify it by replacing the first two clauses with

我最初的实现也会在数组和空字符串上返回true。这个实现没有这个缺陷。如果val不是一个字符串或数字,或者它是一个空字符串,那么它还可以提前返回,在这些情况下会更快。您可以进一步修改它,将前两个子句替换为

typeof(val) != "number"

if you only want to match literal numbers (and not strings)

如果您只想匹配文字数字(而不是字符串)

Edit:

编辑:

I can't post comments yet, so I'm adding this to my answer. The benchmark posted by @Asok is very informative; however, the fastest function does not fit the requirements, as it also returns TRUE for floats, arrays, booleans, and empty strings.

我现在还不能发表评论,所以我要在我的回答中加上这个。@Asok发布的基准非常有用;但是,最快的函数不符合要求,因为它还返回浮点数、数组、布尔值和空字符串。

I created the following test suite to test each of the functions, adding my answer to the list, as well (function 8, which parses strings, and function 9, which does not):

我创建了以下测试套件来测试每个函数,并将我的答案添加到列表中(函数8解析字符串,函数9不解析字符串):

funcs = [
    function(n) {
        return n % 1 == 0;
    },
    function(n) {
        return typeof n === 'number' && n % 1 == 0;
    },
    function(n) {
        return typeof n === 'number' && parseFloat(n) == parseInt(n, 10) && !isNaN(n);
    },
    function(n) {
        return n.toString().indexOf('.') === -1;
    },
    function(n) {
        return n === +n && n === (n|0);
    },
    function(n) {
        return parseInt(n) === n;
    },
    function(n) {
        return /^-?[0-9]+$/.test(n.toString());
    },
    function(n) {
        if ((undefined === n) || (null === n)) {
            return false;
        }
        if (typeof n == 'number') {
            return true;
        }
        return !isNaN(n - 0);
    },
    function(n) {
        return ["string","number"].indexOf(typeof(n)) > -1 && n !== '' && !isNaN(n+".0");
    }
];
vals = [
    [1,true],
    [-1,true],
    [1.1,false],
    [-1.1,false],
    [[],false],
    [{},false],
    [true,false],
    [false,false],
    [null,false],
    ["",false],
    ["a",false],
    ["1",null],
    ["-1",null],
    ["1.1",null],
    ["-1.1",null]
];

for (var i in funcs) {
    var pass = true;
    console.log("Testing function "+i);
    for (var ii in vals) {
        var n = vals[ii][0];
        var ns;
        if (n === null) {
            ns = n+"";
        } else {
            switch (typeof(n)) {
                case "string":
                    ns = "'" + n + "'";
                    break;
                case "object":
                    ns = Object.prototype.toString.call(n);
                    break;
                default:
                    ns = n;
            }
            ns = "("+typeof(n)+") "+ns;
        }

        var x = vals[ii][1];
        var xs;
        if (x === null) {
            xs = "(ANY)";
        } else {
            switch (typeof(x)) {
                case "string":
                    xs = "'" + n + "'";
                    break;
                case "object":
                    xs = Object.prototype.toString.call(x);
                    break;
                default:
                    xs = x;
            }
            xs = "("+typeof(x)+") "+xs;
        }

        var rms;
        try {
            var r = funcs[i](n);
            var rs;
            if (r === null) {
                rs = r+"";
            } else {
                switch (typeof(r)) {
                    case "string":
                        rs = "'" + r + "'";
                        break;
                    case "object":
                        rs = Object.prototype.toString.call(r);
                        break;
                    default:
                        rs = r;
                }
                rs = "("+typeof(r)+") "+rs;
            }

            var m;
            var ms;
            if (x === null) {
                m = true;
                ms = "N/A";
            } else if (typeof(x) == 'object') {
                m = (xs === rs);
                ms = m;
            } else {
                m = (x === r);
                ms = m;
            }
            if (!m) {
                pass = false;
            }
            rms = "Result: "+rs+", Match: "+ms;
        } catch (e) {
            rms = "Test skipped; function threw exception!"
        }

        console.log("    Value: "+ns+", Expect: "+xs+", "+rms);
    }
    console.log(pass ? "PASS!" : "FAIL!");
}

I also reran the benchmark with function #8 added to the list. I won't post the result, as they're a bit embarrassing (e.g. that function is NOT fast)...

我还重新运行了将函数#8添加到列表中的基准。我不会发布结果,因为他们有点尴尬(例如,功能不快速)……

The (abridged -- I removed successful tests, since the output is quite long) results are as follows:

(删节——我删除了成功的测试,因为输出很长)结果如下:

Testing function 0
Value: (object) [object Array], Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (boolean) true, Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (boolean) false, Expect: (boolean) false, Result: (boolean) true, Match: false
Value: null, Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (string) '', Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (string) '1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '-1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
FAIL!

Testing function 1
Value: (string) '1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
PASS!

Testing function 2
Value: (string) '1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
PASS!

Testing function 3
Value: (object) true, Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (object) false, Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (boolean) [object Array], Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (boolean) [object Object], Expect: (boolean) false, Result: (boolean) true, Match: false
Value: null, Expect: (boolean) false, Test skipped; function threw exception!
Value: (string) '', Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (string) 'a', Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (string) '1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '-1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
FAIL!

Testing function 4
Value: (string) '1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
PASS!

Testing function 5
Value: (string) '1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
PASS!

Testing function 6
Value: null, Expect: (boolean) false, Test skipped; function threw exception!
Value: (string) '1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '-1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
PASS!

Testing function 7
Value: (number) 1.1, Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (number) -1.1, Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (object) true, Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (boolean) [object Array], Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (boolean) [object Object], Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (string) '', Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (string) '1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '-1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '1.1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '-1.1', Expect: (ANY), Result: (boolean) true, Match: N/A
FAIL!

Testing function 8
Value: (string) '1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '-1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
PASS!

Testing function 9
Value: (string) '1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
PASS!

I've left in failures so you can see where each function is failing, and the (string) '#' tests so you can see how each function handles integer and float values in strings, as some may want these parsed as numbers and some may not.

我在失败中留下了这样你们可以看到每个函数失败的地方,以及(字符串)'#'测试,这样您就可以看到每个函数如何处理字符串中的整数和浮点值,因为有些函数可能希望将这些值解析为数字,有些则不是。

Out of the 10 functions tested, the ones that actually fit OP's requirements are [1,3,5,6,8,9]

在测试的10个函数中,符合OP要求的是[1,3,5,6,8,9]

#25


1  

Condtion for floating validation :

浮动验证协议:

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

Condtion for Integer validation :

整数验证的Condtion:

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

Hope this might be helpful.

希望这能有所帮助。

#26


1  

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

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

You can add typeof a === 'number' if you want to exclude strings.

如果您想排除字符串,可以添加a == 'number'。

#27


1  

YourJS provides the following two functions which work for all numbers including returning false for -Infinity and Infinity:

YourJS提供了以下两个函数,适用于所有数,包括-∞和∞返回false:

function isFloat(x) {
  return typeOf(x, 'Number') && !!(x % 1);
}

function isInt(x) {
  return typeOf(x, 'Number') && x % 1 == 0;
}

Due to the fact that typeOf() is a YourJS internal function, if you wanted to use these definitions you can download the version for just these functions here: http://yourjs.com/snippets/build/34

由于typeOf()是一个YourJS内部函数,如果您想使用这些定义,您可以在这里下载这些函数的版本:http://yourjs.com/snippets/build/34

#28


1  

Some times Number objects don't allow you to use direct the mod operator (%), if you are facing that case you can use this solution.

有些时候,Number对象不允许您使用direct mod运算符(%),如果您遇到这种情况,您可以使用这个解决方案。

if(object instanceof Number ){
   if( ((Number) object).doubleValue() % 1 == 0 ){
      //your object is an integer
   }
   else{
      //your object is a double
   }
}

#29


1  

This solution worked for me.

这个办法对我起作用了。

<html>
<body>
  <form method="post" action="#">
    <input type="text" id="number_id"/>
    <input type="submit" value="send"/>
  </form>
  <p id="message"></p>
  <script>
    var flt=document.getElementById("number_id").value;
    if(isNaN(flt)==false && Number.isInteger(flt)==false)
    {
     document.getElementById("message").innerHTML="the number_id is a float ";
    }
   else 
   {
     document.getElementById("message").innerHTML="the number_id is a Integer";
   }
  </script>
</body>
</html>

#30


0  

Based on all that I have seen here, I've created my own set of functions to test for what I need:

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

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

However, shime's solution is shorter and with less checks, so it might be a better one.

然而,shime的解决方案更短,检查次数更少,所以它可能是一个更好的解决方案。

#1


1063  

check for a remainder when dividing by 1:

除1时检查余数:

function isInt(n) {
   return n % 1 === 0;
}

If you don't know that the argument is a number you need two tests:

如果你不知道参数是一个数字,你需要两个测试:

function isInt(n){
    return Number(n) === n && n % 1 === 0;
}

function isFloat(n){
    return Number(n) === n && n % 1 !== 0;
}

#2


142  

Try these functions to test whether a value is a number primitive value that has no fractional part and is within the size limits of what can be represented as an exact integer.

尝试使用这些函数来测试一个值是否是一个没有小数部分的数字原语值,并且是否在可以表示为精确整数的大小范围内。

function isFloat(n) {
    return n === +n && n !== (n|0);
}

function isInteger(n) {
    return n === +n && n === (n|0);
}

#3


81  

Why not something like this:

为什么不像这样:

var isInt = function(n) { return parseInt(n) === n };

#4


48  

There is a method called Number.isInteger() which is currently implemented only in latest Firefox and is still a part of EcmaScript 6 proposal. However MDN provides a polyfill for the other browsers, which matches the one specified in ECMA harmony:

有一个方法叫做Number.isInteger(),它目前只在最新的Firefox中实现,仍然是EcmaScript 6提案的一部分。但是MDN为其他浏览器提供了一个polyfill,它与ECMA harmony中指定的浏览器匹配:

if (!Number.isInteger) {
  Number.isInteger = function isInteger (nVal) {
    return typeof nVal === "number" && isFinite(nVal) && nVal > -9007199254740992 && nVal < 9007199254740992 && Math.floor(nVal) === nVal;
  };
}

#5


33  

You can use a simple regular expression:

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

function isInt(value) {

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

    return er.test(value);
}

Or you can use the below functions too, according your needs. They are developed by the PHPJS Project.

也可以根据需要使用下面的函数。它们是由PHPJS项目开发的。

is_int() => Check if variable type is integer and if its content is integer

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

is_float() => Check if variable type is float and if its content is float

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

ctype_digit() => Check if variable type is string and if its content has only decimal digits

ctype_digit() =>检查变量类型是否是字符串,如果它的内容只有小数位数。

Update 1

更新1

Now it checks negative numbers too, thanks for @ChrisBartley comment!

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

#6


17  

Here are efficient functions that check if the value is a number or can be safely converted to a number:

这里有一些有效的函数,可以检查值是一个数字还是可以安全地转换为一个数字:

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

And for integers (would return false if the value is a float):

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

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

The efficiency here is that parseInt (or parseNumber) are avoided when the value already is a number. Both parsing functions always convert to string first and then attempt to parse that string, which would be a waste if the value already is a number.

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

Thank you to the other posts here for providing further ideas for optimization!

感谢这里的其他帖子为优化提供了更多的思路!

#7


11  

function isInteger(x) { return typeof x === "number" && isFinite(x) && Math.floor(x) === x; }
function isFloat(x) { return !!(x % 1); }

// give it a spin

isInteger(1.0);        // true
isFloat(1.0);          // false
isFloat(1.2);          // true
isInteger(1.2);        // false
isFloat(1);            // false
isInteger(1);          // true    
isFloat(2e+2);         // false
isInteger(2e+2);       // true
isFloat('1');          // false
isInteger('1');        // false
isFloat(NaN);          // false
isInteger(NaN);        // false
isFloat(null);         // false
isInteger(null);       // false
isFloat(undefined);    // false
isInteger(undefined);  // false

#8


9  

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

works for all cases.

适用于所有情况。

#9


6  

As others mentioned, you only have doubles in JS. So how do you define a number being an integer? Just check if the rounded number is equal to itself:

正如其他人提到的,在JS中只有替身。那么如何定义一个数字为整数呢?只需检查整数是否等于它本身:

function isInteger(f) {
    return typeof(f)==="number" && Math.round(f) == f;
}
function isFloat(f) { return typeof(f)==="number" && !isInteger(f); }

#10


6  

Here's what I use for integers:

这是我对整数的用法:

Math.ceil(parseFloat(val)) === val

Short, nice :) Works all the time. This is what David Flanagan suggests if I'm not mistaken.

短小的,漂亮的:)一直有效。如果我没弄错的话,这就是大卫·弗拉纳根的建议。

#11


5  

Any Float number with a zero decimal part (e.g. 1.0, 12.00, 0.0) are implicitly cast to Integer, so it is not possible to check if they are Float or not.

任何带有零位小数部分(如1.0、12.00、0.0)的浮点数都被隐式地转换为整数,因此不可能检查它们是否为浮点数。

#12


4  

!!(24%1) // false
!!(24.2%1) // true

#13


4  

var isInt = function (n) { return n === (n | 0); };

Haven't had a case where this didn't do the job.

还没有这样的例子。

#14


3  

It really depends on what you want to achieve. If you want to "emulate" strongly typed languages then I suggest you not trying. As others mentioned all numbers have the same representation (the same type).

这真的取决于你想要实现什么。如果您想要“模仿”强类型语言,那么我建议您不要尝试。正如其他人所提到的,所有数字都有相同的表示形式(相同的类型)。

Using something like Claudiu provided:

使用类似克劳迪斯提供的:

isInteger( 1.0 ) -> true

isInteger(1.0) -> true

which looks fine for common sense, but in something like C you would get false

这看起来很符合常识,但是像C,你会得到错误?

#15


3  

It's simple as:

很简单:

if( n === parseInt(n) ) ...

Try this in console:

在控制台试试这个:

x=1;
x===parseInt(x); // true
x="1";
x===parseInt(x); // false
x=1.1;
x===parseInt(x); // false, obviously

// BUT!

x=1.0;
x===parseInt(x); // true, because 1.0 is NOT a float!

This confuses a lot of people. Whenever something is .0, it's not a float anymore. It's an integer. Or you can just call it "a numeric thing" for there is no strict distinction like back then in C. Good old times.

这让很多人感到困惑。当一个东西是。0时,它就不再是一个浮点数了。它是一个整数。或者你可以叫它“一个数字的东西”,因为没有严格的区别,就像在c。

So basically, all you can do is check for integer accepting the fact that 1.000 is an integer.

基本上,你能做的就是检查整数接受1。000是整数的事实。

Interesting side note

有趣的边注

There was a comment about huge numbers. Huge numbers mean NO problem for this approach; whenever parseInt is unable to handle the number (for it's too big) it will return something else than the actual value so the test will return FALSE. This is a good thing because if you consider something a "number" you normally expect JS to be able to calculate with it - so yes, numbers are limited and parseInt will take this into consideration, to put it this way.

有一个关于巨大数字的评论。庞大的数字意味着这种方法没有问题;当parseInt无法处理这个数字(因为它太大了)时,它将返回一些其他的东西,而不是实际的值,因此测试将返回FALSE。这是一件好事,因为如果你考虑一个“数字”,你通常希望JS能够用它来计算——是的,数字是有限的,parseInt会考虑这个,这样说。

Try this:

试试这个:

<script>

var a = 99999999999999999999;
var b = 999999999999999999999; // just one more 9 will kill the show!
var aIsInteger = (a===parseInt(a))?"a is ok":"a fails";
var bIsInteger = (b===parseInt(b))?"b is ok":"b fails";
alert(aIsInteger+"; "+bIsInteger);

</script>

In my browser (IE8) this returns "a is ok; b fails" which is exactly because of the huge number in b. The limit may vary but I guess 20 digits "ought to be enough for anybody", to quote a classical :)

在我的浏览器(IE8)中,这返回“a是ok的;b不及格“这正是因为b里面有很多数字。限制可能会变化,但我猜20位数字“应该对任何人都足够了”,引用一句经典的话:)

#16


2  

THIS IS FINAL CODE FOR CHECK BOTH INT AND FLOAT

这是检查INT和FLOAT的最终代码

function isInt(n) { 
   if(typeof n == 'number' && Math.Round(n) % 1 == 0) {
       return true;
   } else {
       return false;
   }
} 

OR

function isInt(n) {   
   return typeof n == 'number' && Math.Round(n) % 1 == 0;   
}   

#17


2  

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

#18


2  

I wrote function which accepts strings (if somebody will need)

我写了一个接受字符串的函数(如果有人需要的话)

function isInt(x) {
    return !isNaN(x) && eval(x).toString().length == parseInt(eval(x)).toString().length
}

function isFloat(x) {
    return !isNaN(x) && !isInt(eval(x)) && x.toString().length > 0
}

example ouptuts:

示例ouptuts:

console.log(isFloat('0.2'))  // true
console.log(isFloat(0.2))    // true
console.log(isFloat('.2'))   // true
console.log(isFloat('-.2'))  // true
console.log(isFloat(-'.2'))  // true
console.log(isFloat(-.2))    // true
console.log(isFloat('u.2'))  // false
console.log(isFloat('2'))    // false
console.log(isFloat('0.2u')) // false

console.log(isInt('187'))  // true
console.log(isInt(187))    // true
console.log(isInt('1.2'))  // false
console.log(isInt('-2'))   // true
console.log(isInt(-'1'))   // true
console.log(isInt('10e1')) // true
console.log(isInt(10e1))   // true

#19


1  

For integers I use this

对于整数,我用这个

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

#20


1  

It really doesn't have to be so complicated. The numeric value of an integer's parseFloat() and parseInt() equivalents will be the same. Thus you can do like so:

真的不需要这么复杂。整数的parseFloat()和parseInt()等价物的数值是相同的。因此你可以这样做:

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

Then

然后

if (isInt(x)) // do work

This will also allow for string checks and thus is not strict. If want a strong type solution (aka, wont work with strings):

这也将允许字符串检查,因此不严格。如果想要强类型的解决方案(比如,不能使用字符串):

function is_int(value){ return !isNaN(parseInt(value * 1) }

#21


1  

In java script all the numbers are internally 64 bit floating point, same as double in java. There are no diffrent types in javascript, all are represented by type number. Hence you wil l not be able make a instanceof check. However u can use the above solutions given to find out if it is a fractional number. designers of java script felt with a single type they can avoid numerous type cast errors.

在java脚本中,所有数字在内部都是64位浮点数,与java中的双精度浮点数相同。javascript中没有不同的类型,所有类型都用类型号表示。因此你就不能做一个instanceof检查。但是你可以使用上面给出的解来确定它是否是小数。java脚本的设计人员感觉只有一种类型,他们可以避免许多类型转换错误。

#22


1  

This maybe isn't as performant as the % answer, which prevents you from having to convert to a string first, but I haven't seen anyone post it yet, so here's another option that should work fine:

这可能不像%答案那样的性能,它阻止您首先转换成字符串,但是我还没有看到任何人发布它,所以这里有另外一个选项应该可以正常工作:

function isInteger(num) {
    return num.toString().indexOf('.') === -1;
}

#23


1  

Here's my code. It checks to make sure it's not an empty string (which will otherwise pass) and then converts it to numeric format. Now, depending on whether you want '1.1' to be equal to 1.1, this may or may not be what you're looking for.

这是我的代码。它检查以确保它不是一个空字符串(否则会通过),然后将其转换为数字格式。现在,根据你想要1.1是否等于1。1,这可能是你想要的,也可能不是。

var isFloat = function(n) {
    n = n.length > 0 ? Number(n) : false;
    return (n === parseFloat(n));
};
var isInteger = function(n) {
    n = n.length > 0 ? Number(n) : false;
    return (n === parseInt(n));
};

var isNumeric = function(n){

   if(isInteger(n) || isFloat(n)){
        return true;
   }
   return false;

};

#24


1  

I like this little function, which will return true for both positive and negative integers:

我喜欢这个小函数,它对于正整数和负整数都是成立的:

function isInt(val) {
    return ["string","number"].indexOf(typeof(val)) > -1 && val !== '' && !isNaN(val+".0");
}

This works because 1 or "1" becomes "1.0", which isNaN() returns false on (which we then negate and return), but 1.0 or "1.0" becomes "1.0.0", while "string" becomes "string.0", neither of which are numbers, so isNaN() returns false (and, again, gets negated).

这是因为1或“1”变成了“1.0”,isNaN()返回false(然后我们将其否定并返回),而1.0或“1.0”变成了“1.0.0”,而“string”变成了“string”。0",它们都不是数字,所以isNaN()返回false(并且,同样,被否定)。

If you only want positive integers, there's this variant:

如果你只想要正整数,有这个变量:

function isPositiveInt(val) {
    return ["string","number"].indexOf(typeof(val)) > -1 && val !== '' && !isNaN("0"+val);
}

or, for negative integers:

或者,负整数:

function isNegativeInt(val) {
    return `["string","number"].indexOf(typeof(val)) > -1` && val !== '' && isNaN("0"+val);
}

isPositiveInt() works by moving the concatenated numeric string ahead of the value to be tested. For example, isPositiveInt(1) results in isNaN() evaluating "01", which evaluates false. Meanwhile, isPositiveInt(-1) results in isNaN() evaluating "0-1", which evaluates true. We negate the return value and that gives us what we want. isNegativeInt() works similarly, but without negating the return value of isNaN().

isPositiveInt()的工作方式是将连接的数字字符串移动到要测试的值之前。例如,isPositiveInt(1)导致isNaN()计算“01”,它计算false。与此同时,isPositiveInt(-1)结果isNaN()对“0-1”进行评估,该评估为true。我们减去返回值,得到我们想要的。isNegativeInt()的工作原理类似,但不会否定isNaN()的返回值。

Edit:

编辑:

My original implementation would also return true on arrays and empty strings. This implementation doe not have that defect. It also has the benefit of returning early if val is not a string or number, or if it's an empty string, making it faster in these cases. You can further modify it by replacing the first two clauses with

我最初的实现也会在数组和空字符串上返回true。这个实现没有这个缺陷。如果val不是一个字符串或数字,或者它是一个空字符串,那么它还可以提前返回,在这些情况下会更快。您可以进一步修改它,将前两个子句替换为

typeof(val) != "number"

if you only want to match literal numbers (and not strings)

如果您只想匹配文字数字(而不是字符串)

Edit:

编辑:

I can't post comments yet, so I'm adding this to my answer. The benchmark posted by @Asok is very informative; however, the fastest function does not fit the requirements, as it also returns TRUE for floats, arrays, booleans, and empty strings.

我现在还不能发表评论,所以我要在我的回答中加上这个。@Asok发布的基准非常有用;但是,最快的函数不符合要求,因为它还返回浮点数、数组、布尔值和空字符串。

I created the following test suite to test each of the functions, adding my answer to the list, as well (function 8, which parses strings, and function 9, which does not):

我创建了以下测试套件来测试每个函数,并将我的答案添加到列表中(函数8解析字符串,函数9不解析字符串):

funcs = [
    function(n) {
        return n % 1 == 0;
    },
    function(n) {
        return typeof n === 'number' && n % 1 == 0;
    },
    function(n) {
        return typeof n === 'number' && parseFloat(n) == parseInt(n, 10) && !isNaN(n);
    },
    function(n) {
        return n.toString().indexOf('.') === -1;
    },
    function(n) {
        return n === +n && n === (n|0);
    },
    function(n) {
        return parseInt(n) === n;
    },
    function(n) {
        return /^-?[0-9]+$/.test(n.toString());
    },
    function(n) {
        if ((undefined === n) || (null === n)) {
            return false;
        }
        if (typeof n == 'number') {
            return true;
        }
        return !isNaN(n - 0);
    },
    function(n) {
        return ["string","number"].indexOf(typeof(n)) > -1 && n !== '' && !isNaN(n+".0");
    }
];
vals = [
    [1,true],
    [-1,true],
    [1.1,false],
    [-1.1,false],
    [[],false],
    [{},false],
    [true,false],
    [false,false],
    [null,false],
    ["",false],
    ["a",false],
    ["1",null],
    ["-1",null],
    ["1.1",null],
    ["-1.1",null]
];

for (var i in funcs) {
    var pass = true;
    console.log("Testing function "+i);
    for (var ii in vals) {
        var n = vals[ii][0];
        var ns;
        if (n === null) {
            ns = n+"";
        } else {
            switch (typeof(n)) {
                case "string":
                    ns = "'" + n + "'";
                    break;
                case "object":
                    ns = Object.prototype.toString.call(n);
                    break;
                default:
                    ns = n;
            }
            ns = "("+typeof(n)+") "+ns;
        }

        var x = vals[ii][1];
        var xs;
        if (x === null) {
            xs = "(ANY)";
        } else {
            switch (typeof(x)) {
                case "string":
                    xs = "'" + n + "'";
                    break;
                case "object":
                    xs = Object.prototype.toString.call(x);
                    break;
                default:
                    xs = x;
            }
            xs = "("+typeof(x)+") "+xs;
        }

        var rms;
        try {
            var r = funcs[i](n);
            var rs;
            if (r === null) {
                rs = r+"";
            } else {
                switch (typeof(r)) {
                    case "string":
                        rs = "'" + r + "'";
                        break;
                    case "object":
                        rs = Object.prototype.toString.call(r);
                        break;
                    default:
                        rs = r;
                }
                rs = "("+typeof(r)+") "+rs;
            }

            var m;
            var ms;
            if (x === null) {
                m = true;
                ms = "N/A";
            } else if (typeof(x) == 'object') {
                m = (xs === rs);
                ms = m;
            } else {
                m = (x === r);
                ms = m;
            }
            if (!m) {
                pass = false;
            }
            rms = "Result: "+rs+", Match: "+ms;
        } catch (e) {
            rms = "Test skipped; function threw exception!"
        }

        console.log("    Value: "+ns+", Expect: "+xs+", "+rms);
    }
    console.log(pass ? "PASS!" : "FAIL!");
}

I also reran the benchmark with function #8 added to the list. I won't post the result, as they're a bit embarrassing (e.g. that function is NOT fast)...

我还重新运行了将函数#8添加到列表中的基准。我不会发布结果,因为他们有点尴尬(例如,功能不快速)……

The (abridged -- I removed successful tests, since the output is quite long) results are as follows:

(删节——我删除了成功的测试,因为输出很长)结果如下:

Testing function 0
Value: (object) [object Array], Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (boolean) true, Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (boolean) false, Expect: (boolean) false, Result: (boolean) true, Match: false
Value: null, Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (string) '', Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (string) '1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '-1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
FAIL!

Testing function 1
Value: (string) '1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
PASS!

Testing function 2
Value: (string) '1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
PASS!

Testing function 3
Value: (object) true, Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (object) false, Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (boolean) [object Array], Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (boolean) [object Object], Expect: (boolean) false, Result: (boolean) true, Match: false
Value: null, Expect: (boolean) false, Test skipped; function threw exception!
Value: (string) '', Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (string) 'a', Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (string) '1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '-1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
FAIL!

Testing function 4
Value: (string) '1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
PASS!

Testing function 5
Value: (string) '1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
PASS!

Testing function 6
Value: null, Expect: (boolean) false, Test skipped; function threw exception!
Value: (string) '1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '-1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
PASS!

Testing function 7
Value: (number) 1.1, Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (number) -1.1, Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (object) true, Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (boolean) [object Array], Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (boolean) [object Object], Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (string) '', Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (string) '1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '-1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '1.1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '-1.1', Expect: (ANY), Result: (boolean) true, Match: N/A
FAIL!

Testing function 8
Value: (string) '1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '-1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
PASS!

Testing function 9
Value: (string) '1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
PASS!

I've left in failures so you can see where each function is failing, and the (string) '#' tests so you can see how each function handles integer and float values in strings, as some may want these parsed as numbers and some may not.

我在失败中留下了这样你们可以看到每个函数失败的地方,以及(字符串)'#'测试,这样您就可以看到每个函数如何处理字符串中的整数和浮点值,因为有些函数可能希望将这些值解析为数字,有些则不是。

Out of the 10 functions tested, the ones that actually fit OP's requirements are [1,3,5,6,8,9]

在测试的10个函数中,符合OP要求的是[1,3,5,6,8,9]

#25


1  

Condtion for floating validation :

浮动验证协议:

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

Condtion for Integer validation :

整数验证的Condtion:

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

Hope this might be helpful.

希望这能有所帮助。

#26


1  

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

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

You can add typeof a === 'number' if you want to exclude strings.

如果您想排除字符串,可以添加a == 'number'。

#27


1  

YourJS provides the following two functions which work for all numbers including returning false for -Infinity and Infinity:

YourJS提供了以下两个函数,适用于所有数,包括-∞和∞返回false:

function isFloat(x) {
  return typeOf(x, 'Number') && !!(x % 1);
}

function isInt(x) {
  return typeOf(x, 'Number') && x % 1 == 0;
}

Due to the fact that typeOf() is a YourJS internal function, if you wanted to use these definitions you can download the version for just these functions here: http://yourjs.com/snippets/build/34

由于typeOf()是一个YourJS内部函数,如果您想使用这些定义,您可以在这里下载这些函数的版本:http://yourjs.com/snippets/build/34

#28


1  

Some times Number objects don't allow you to use direct the mod operator (%), if you are facing that case you can use this solution.

有些时候,Number对象不允许您使用direct mod运算符(%),如果您遇到这种情况,您可以使用这个解决方案。

if(object instanceof Number ){
   if( ((Number) object).doubleValue() % 1 == 0 ){
      //your object is an integer
   }
   else{
      //your object is a double
   }
}

#29


1  

This solution worked for me.

这个办法对我起作用了。

<html>
<body>
  <form method="post" action="#">
    <input type="text" id="number_id"/>
    <input type="submit" value="send"/>
  </form>
  <p id="message"></p>
  <script>
    var flt=document.getElementById("number_id").value;
    if(isNaN(flt)==false && Number.isInteger(flt)==false)
    {
     document.getElementById("message").innerHTML="the number_id is a float ";
    }
   else 
   {
     document.getElementById("message").innerHTML="the number_id is a Integer";
   }
  </script>
</body>
</html>

#30


0  

Based on all that I have seen here, I've created my own set of functions to test for what I need:

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

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

However, shime's solution is shorter and with less checks, so it might be a better one.

然而,shime的解决方案更短,检查次数更少,所以它可能是一个更好的解决方案。