855

How to find that a number is float or integer?

1.25 --> float  
1 --> integer  
0 --> integer  
0.25 --> float
Sinister Beard
  • 3,570
  • 12
  • 59
  • 95
coure2011
  • 40,286
  • 83
  • 216
  • 349
  • 53
    I understand what you're asking here, but just to be clear: `` JavaScript does not have different integer and float numeric types. Every number in JavaScript is just a `Number`. `` – Matt Ball Oct 07 '10 at 21:01
  • 5
    Is `Infinity`an integer or a non-integer value as far as you're concerned? The answers here are pretty evenly distributed on this score. – Mike Samuel Mar 13 '12 at 07:07
  • 13
    @MikeSamuel To be mathematically accurate: since infinity is not a real number and all integers are real numbers, `Infinity` cannot be considered an integer. – rvighne Feb 15 '14 at 18:54
  • @rvighne, The question asks about "float", not "real". Either way, reals are irrelevant because computers can only represent [computable numbers](http://en.wikipedia.org/wiki/Computable_number). – Mike Samuel Feb 15 '14 at 21:33
  • @MikeSamuel Sorry, I meant integers *and floats* are real numbers. And anyway, I said that ints and floats are **part of** real numbers, not that they can represent all reals. Basically, my point is that Infinity is not a number and you shouldn't care whether it's a float or int. – rvighne Feb 16 '14 at 00:55
  • 2
    @rvighne, I think we agree that the fact that the infinities and NaN are not real numbers means that IEEE-754 floats are not a subset of real numbers. All numerical analysis based on IEEE-754 has to deal with this fact. What I don't understand is how you think this fact determines how is_integral should behave w.r.t. cardinalities. Personally, I think ((x % 1) == 0) is a good proxy and is fully specified by IEEE-754, so there's no need to argue about correspondances between different number lines. – Mike Samuel Feb 16 '14 at 13:33
  • @Mike "The IEEE 754 “remainder” operation computes the remainder from a rounding division, not a truncating division, and so its behaviour is not analogous to that of the usual integer remainder operator. Instead the ECMAScript language defines % on floating-point operations to behave in a manner analogous to that of the Java integer remainder operator; this may be compared with the C library function fmod." http://www.ecma-international.org/ecma-262/5.1/ – seo Feb 07 '15 at 01:11
  • Counting can only be done with integers so countable infinity is a integer. nb Cantor proved there are more real numbers than a countable infinite set. (http://mathworld.wolfram.com/CountablyInfinite.html) – QuentinUK Mar 18 '15 at 00:24
  • A good paper on the floating point specs. https://ece.uwaterloo.ca/~dwharder/NumericalAnalysis/02Numerics/Double/paper.pdf – seo Mar 28 '15 at 14:00
  • 1
    You can use the Number method `isInteger`. Check it [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger). – Timbergus Dec 17 '15 at 16:18
  • http://jsben.ch/#/htLVw - a benchmark for the common ways to do it – EscapeNetscape Oct 24 '16 at 17:45
  • 5
    Do you consider `1.0` integer or float? – vol7ron Jul 12 '18 at 02:18

51 Answers51

1484

check for a remainder when dividing by 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;
}

Update 2019 5 years after this answer was written, a solution was standardized in ECMA Script 2015. That solution is covered in this answer.

Omn
  • 2,982
  • 1
  • 26
  • 39
kennebec
  • 102,654
  • 32
  • 106
  • 127
  • 147
    Careful, this will also return true for an empty string, a string representing an integral number, `true`, `false`, `null`, an empty array, an array containing a single integral number, an array containing a string representing an integral number, and maybe more. – Dagg Nabbit Oct 08 '10 at 16:53
  • I think your first implementation is brilliant and efficient and the second redundant. Right? – woods Nov 10 '11 at 11:33
  • 4
    Just to note, this method will work in most cases, but its not enough to assume that the converse (!isInt) implies a float. Try it against a very large number - !isInt(Number.MAX_VALUE-0.1)- it won't work. This is due to the use of modulo. The methods in the answer below this *will* work in all cases. – VLostBoy Mar 05 '12 at 13:22
  • Thanks, even if JavaScript does not differ between float and int, this is extremely useful for translation: http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html – SimonSimCity Apr 10 '12 at 09:56
  • 22
    Nice trick but not the correct answer as it fails to check empty string `""` and `1.0` `isInt("");` && `isInt(1.0);` both result in `true` see this demo http://jsbin.com/elohuq/1/edit – GajendraSinghParihar Oct 04 '12 at 09:43
  • Why the use of === vs == ? – ina Jul 29 '13 at 04:34
  • 9
    Ina, the use of === is encouraged over == in general, because it leads to more type safety and more predictable, uniform behaviour. As previous answerers have stated, this answer is absolutely, 100% incorrect. The values null, empty string, 1.0 and numerous others will all register incorrectly as integers (even with the === check). – whoblitz Sep 11 '13 at 02:59
  • isInt(1.000000000000000000000000001) === true – Frank Fang Jan 23 '14 at 11:26
  • 3
    It's an accepted answer with 383 thumbs up right now but it's just wrong. I mean, it's like a workaround that doesn't take you where you wanted to go. It's an anti-pattern. – dkellner Apr 28 '14 at 19:36
  • 3
    Worst answer on SO? `null % 1 === 0`, `[] % 1 === 0` – Skylar Saveland Oct 03 '14 at 04:07
  • 64
    The question was how to check if a number is an integer, not how to check any value. – kennebec Oct 03 '14 at 14:31
  • 2
    would you still use it or go for the new Number.isInteger() ? – Dukeatcoding Oct 07 '14 at 08:49
  • it's not wrong. 1.000000000000000000000000001 === 1 – andrewrk Oct 29 '14 at 07:05
  • Wrong for reasons described above. It validates an empty input field as containing an integer. – stef Nov 13 '14 at 14:56
  • 1
    Note that second `isInt` may got `false` with `isInt(new Number(0))`. – tsh Feb 03 '15 at 05:11
  • `4ff` returns true. Is that expected? – dotty Apr 13 '15 at 13:05
  • May i ask why you use `Number(n) === n` and not `typeof n === "number"`? I guess it depends on the intention what you use, but the first also is true if `n === "5"`, for example. – JimmyMcHoover May 28 '15 at 18:45
  • does not work for me. n === Number(n) always fail and returns false. – JGV Jun 01 '15 at 18:44
  • 30
    A lot of hostile comments about how it doesn't validate strings. That's not part of the OP's question. If I go onto SO to ask a question about retrieving the last element of an array and someone answers with `function last (array) { return array[array.length - 1]; }`, is it "just wrong" or "Worst answer on SO" because it doesn't check if the argument is an array first? Yes, good practice to check arguments, but that's developer responsibility. SO answers should be short and directly answer the question as clearly as possible. – M Miller Jun 13 '15 at 22:17
  • It does not work with using ===. At least, in Firefox. But it DOES work, if to use ==. – Alexander Sep 09 '15 at 00:05
  • This is invalid code and will fail with numbers like 1.2 because this number become close-to 1.2 but not 1.2 `test: 1.2 false ::: 0.19999999999999996` – Lukas Liesis Jul 20 '17 at 12:48
  • pretty sure that is modulus % and not dividing / – luckyguy73 Apr 09 '18 at 22:49
167

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);
}
Dagg Nabbit
  • 75,346
  • 19
  • 113
  • 141
  • 6
    heh awesom exploit, it's pretty much mine (`n===+n` to check for numeric, `n|0` to round), but with built-in operators. funky – Claudiu Oct 07 '10 at 21:11
  • 7
    @John Hartsock a string is never going to be a numeric value. It's a string. The point of this function is to test whether a value is a Javascript numeric value that has no fractional part and is within the size limits of what can be represented as an exact integer. If you want to check a string to see if it contains a sequence of characters that represent a number, you'd call `parseFloat()` first. – Pointy Oct 07 '10 at 21:23
  • @Pointy but parseFloat("1.1a") will still return 1.1. Suppose you had a text field you wanted to validate that it was an float and only a float without alpha characters. Testing weather a text field from an input element for decimal(float) – John Hartsock Oct 07 '10 at 21:28
  • 4
    @John Hartsock: it won't return true unless a number primitive was passed. I think that makes sense given the names of the functions. Anything else should be a candidate for isString, isBoolean, etc. if such functions are being written. – Dagg Nabbit Oct 08 '10 at 02:43
  • 4
    @Pointy: double precision floats can represent integer values exactly up to 2^53. So it depends if the OP was asking about integer in the maths sense (whole numbers) or in the 32-bit data sense. If it's the latter, your solution is perfect. – djd Feb 18 '12 at 01:26
  • @Dave yes that's true, but note that when JavaScript wants to deal with integers it usually bashes them down to 32 bits. – Pointy Feb 18 '12 at 02:57
  • 2
    +1 for using `n|0` to convert the value to a signed 32-bit integer. As @Dave says, the integers between 2^31 and 2^53 are interesting in JavaScript, because they can be represented exactly, but get truncated to their least-significant 32 bits by the bitwise operators. – TachyonVortex Jul 19 '13 at 02:53
  • @DaggNabbit I've never seen `===+` or `|` in JavaScript before. I understand what @Claudiu said about them but I don't see them mentioned anywhere on w3school. Is there a place I can go to see some documentation on them? I'm going to guess `|` is a bit wise operator, is that right? Is `===+` some kind of addition or maybe its a positive sign operator which would only work on a number? Again I can't find anything about these anywhere. Thanks. – Dan Oct 23 '13 at 21:38
  • 1
    @Dan: `===+` is actually two operators, `===` (strict equality), and then [unary `+`](http://stackoverflow.com/questions/5450076/whats-the-significant-use-of-unary-plus-and-minus-operators), e.g. `(+5)`. the `|` is [bit-wise or](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators), yes. – Claudiu Oct 23 '13 at 21:41
  • 4
    @Dan, Claudiu is right, `===+` was just my lazy formatting. It's fixed now, with Pointy's excellent comment added. Also, w3schools is generally considered to be inaccurate and incomplete; you probably don't want to use it for a reference. Better to stick to docs from MDN, WHATWG, W3C, and the official spec. – Dagg Nabbit Oct 23 '13 at 23:59
  • 1
    The only caveat with this method is that bitwise operators in JavaScript work up until 32 bits, so large numbers will give false as an integer. – Gaston Sanchez Apr 02 '14 at 15:26
  • 1
    @GastónSánchez ISTM if a number cannot be expressed as an unsigned 32-bit int, it is not an "integer" in the context of JavaScript. IOW the only way this question is useful is if it's asking how to identify numbers that can be converted to the format required by bitwise operators without changing their value. Determining whether a number has no fractional part is trivial; I assume that's not what was being asked here. – Dagg Nabbit May 01 '14 at 02:00
  • 8
    in javascript, bitwise operators like `|` (OR) only operate on signed 32-bit integers. OP does not state if the goal is to check for signed int32 values. So this won't work with out of range numbers. `isInteger(5000000000)` will return `false` which is wrong! – Onur Yıldırım Jan 02 '15 at 20:51
  • @OnurYıldırım see comments above. This answer assumes the OP is asking how to determine if a number can be represented as a 32 bit unsigned int. – Dagg Nabbit Jan 02 '15 at 20:58
  • @DaggNabbit well, `isInteger(-1000)` will return `true` which is not an unsigned integer. – Onur Yıldırım Jan 03 '15 at 08:25
  • @OnurYıldırım doh, I meant signed. – Dagg Nabbit Jan 03 '15 at 09:03
  • `n === +n` is redundant in integer test, no? – Mirek Rusin Feb 24 '15 at 00:44
  • 1
    Seems like `1.0` is rejected as a float: `1.0 === +1.0 && 1.0 !== (1.0|0)` >>> `false`. – F Lekschas Jul 28 '15 at 15:35
  • Funny occasion when this doesn't work is when you use `Number`. – Tomáš Zato Nov 13 '15 at 01:27
  • 1
    isFloat(12.0) is false .. ? – django Dec 15 '15 at 06:09
163

There is a method called Number.isInteger() which is currently implemented in everything but IE. MDN also provides a polyfill for other browsers:

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

However, for most uses cases, you are better off using Number.isSafeInteger which also checks if the value is so high/low that any decimal places would have been lost anyway. MDN has a polyfil for this as well. (You also need the isInteger pollyfill above.)

if (!Number.MAX_SAFE_INTEGER) {
    Number.MAX_SAFE_INTEGER = 9007199254740991; // Math.pow(2, 53) - 1;
}
Number.isSafeInteger = Number.isSafeInteger || function (value) {
   return Number.isInteger(value) && Math.abs(value) <= Number.MAX_SAFE_INTEGER;
};
Omn
  • 2,982
  • 1
  • 26
  • 39
paperstreet7
  • 2,058
  • 1
  • 15
  • 18
  • This works in my Chrome now too and probably the way to go in the future – Dukeatcoding Oct 07 '14 at 08:48
  • 1
    In my opinion the best solution. – Automatico Aug 29 '15 at 19:25
  • 8
    `Number.isInteger(12.0) //true` (Chrome, Feb '17) – S Panfilov Jan 31 '17 at 20:11
  • 1
    This with the polyfill is the most reliable and simple solution. – Francesco Pasa Mar 22 '17 at 21:17
  • 8
    @SergeyPanfilov `12.0 ∈ ℤ`. – Константин Ван Aug 28 '17 at 06:53
  • 2
    I'm unaware if the spec has changed since this answer was provided, but note that the above function is not a correct polyfill for `Number.isInteger`. It is, however, a correct polyfill for `Number.isSafeInteger`. `Number.isInteger` should not check whether the number is a "safe integer". See on MDN: [isInteger](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger#Polyfill) and [isSafeInteger](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger#Polyfill). – nunocastromartins Mar 19 '18 at 11:43
  • @Bravo I read too quickly, I though he wanted to use that to know if the value was (float || integer), like 2 checks in one method. – GwenM Aug 13 '21 at 10:55
94

Why not something like this:

var isInt = function(n) { return parseInt(n) === n };
John Conde
  • 217,595
  • 99
  • 455
  • 496
warfares
  • 997
  • 6
  • 2
  • This is actually the core of a good solution for me. I needed to allow positive integers and disallow floats, strings and negative integers. – Imran-UK Jul 09 '13 at 16:48
  • 4
    This seems like a vastly better solution than the others in this thread. Could the community offer some criticism, perhaps? – Stas Bichenko May 05 '14 at 18:06
  • 7
    var y = 1.00; y === parseInt(y, 10); // this returns true for me, which is not really what we want. – whoughton May 31 '14 at 19:11
  • The only "downside" I see is that the given number `n` is converted to a string by `parseInt`. See [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt). But I will use this solution. :) – RhinoDevel Nov 13 '15 at 10:28
  • why is that a downside? it's just converted for comparison – user3787706 Dec 10 '15 at 14:26
  • isInt(1,02) - returns true, but should return false – ekussberg Jan 22 '16 at 10:18
  • 4
    @ekussberg: Why should that return false? 1 is an int. and 02, the second argument, is ignored. – Jonathan Hall Feb 28 '16 at 20:33
  • @Flimzy Some countries use a comma `,` to separate whole number from decimal. Maybe this was the case and @ekussberg made a typo. If it was `1.02`, it would be false as expected. `,` is an operator in JavaScript. –  Jun 07 '16 at 19:43
  • What if the number is very large? parseInt first convert the argument to String, then check if the beginning of the string may convert to some integer. for example, 1e100 is an integer, but `parseInt(1e100)` will got `1` instead of `1e100` which will fail in your solution. – tsh Aug 25 '16 at 05:28
  • This fails if input type is string. Eg: If n="750" it returns false. – Shashank K May 03 '18 at 11:12
  • THIS is what I am looking for! I used this one like [this](https://stackoverflow.com/a/54866825/7265539) for my project. Perfect! – vpibano Feb 25 '19 at 13:02
  • 1
    −1 because converting a number to a string and then parsing it back to a number just to check whether that results in the same value is a ridiculous amount of complexity when all that’s really needed is to check whether a number—already in floating-point form!—is an integer. – wchargin Dec 27 '19 at 02:18
32

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.

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

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

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

Update 1

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

Community
  • 1
  • 1
Marcio Mazzucato
  • 8,841
  • 9
  • 64
  • 79
20
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
shime
  • 8,746
  • 1
  • 30
  • 51
19

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):

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.

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

Tal Liron
  • 340
  • 2
  • 6
12
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.

Deepak Yadav
  • 1,724
  • 3
  • 23
  • 38
  • 3
    +1 This is good. `isInt('1')` returns `true` as expected (at least for me). Weird enough, though, this returns `true` to `isInt([5])` as well. Didn't matter for me, but may for you, so, take care. – acdcjunior Jul 03 '13 at 14:07
  • 2
    isFloat(12.0) is false – django Dec 15 '15 at 06:21
11

2022 update - We could simply use the Number's methods.

Check if integer or float : Number.isFinite(val)

Check if integer : Number.isInteger(val)

Check if float (not integer) : !Number.isInteger(val) && Number.isFinite(val)

Zetura
  • 446
  • 5
  • 12
8

How about this one?

isFloat(num) {
    return typeof num === "number" && !Number.isInteger(num);
}
sheriff_paul
  • 995
  • 2
  • 14
  • 29
8

We can check by isInteger function. ie number will return true and float return false

console.log(Number.isInteger(2)),<BR>

Will return true

console.log(Number.isInteger(2.5))

Will return false

Aryan
  • 3,338
  • 4
  • 18
  • 43
akshay bagade
  • 1,169
  • 1
  • 11
  • 24
7

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:

function isInteger(f) {
    return typeof(f)==="number" && Math.round(f) == f;
}
function isFloat(f) { return typeof(f)==="number" && !isInteger(f); }
Claudiu
  • 224,032
  • 165
  • 485
  • 680
6

Simple integer test:

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

Makes sense: if JavaScript can convert something to an integer, and by the conversion it becomes the exact same thing, then your operand was an integer.

Test cases for 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.

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

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. Look:

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

I tested this in 2014 on IE8, then 2021 on Chrome, both returns "a is ok; b fails" which means if a number is too big, it can't be an integer anymore.

20 digits ought to be enough for anybody, to quote a classic.

dkellner
  • 8,726
  • 2
  • 49
  • 47
  • This is fine if you only need to check for integral numbers (from a math POV), but if you want to make sure they actually *work like integers* (from a computing POV) it's going to be incorrect for huge numbers. See [this comment](http://stackoverflow.com/questions/3885817/how-to-check-if-a-number-is-float-or-integer/3885844#comment11785178_3885844). – Dagg Nabbit Apr 26 '14 at 09:46
  • Mmmmmmm... Why do you think that? I mean, if parseInt returns something and it seems equal to the variable itself, you can be sure your n truly does work as an integer. I found that 99999999999999999999 (that is, 20 times "9") is a number while adding one more "9" makes parseInt fail (returning 1). It may be browser-dependent; however, YES, there is a limit and NO, whatever is off that limit won't return true for the check above. – dkellner Apr 26 '14 at 15:04
  • What I mean is that bitwise operators (which treat numbers as 32 bit ints) won't give the expected results on numbers which can't be represented as 32 bit ints, so those numbers shouldn't be identified as ints. This is in line with how the proposed `Number.isInteger` works. – Dagg Nabbit Apr 27 '14 at 19:57
  • Something can be a true integer without being stored one specific way. I see your point but integers are integers because they don't have a fractional part and can be added/subtracted arbitrarily without getting float-like results. If you treat numbers as bitfields you're supposing something about how they're stored which is - in my opinion - a practically working but not 100% reliable way. If you're looking for "an integer stored in a certain way", well, I'm not sure there is a single-line test you can safely use on all platforms. – dkellner Apr 28 '14 at 19:32
  • Numbers which can be expressed as 32-bit ints do work 100% reliably with bitwise operators. You are not "supposing anything about how they are stored;" the numbers are converted to signed 32-bit big-endian two's complement integers, per specification. Numbers which cannot be represented in this format should not be considered integers. Again, this is in line with how `Number.isInteger` works. A single line test is `n === (n | 0)` as shown in another answer. – Dagg Nabbit Apr 29 '14 at 21:21
  • I don't think this is correct (they're NOT 32 bit ints but 64 bit floats "per specification"); also I don't think our argument here has any added value regarding to the original question. Thanks anyway. – dkellner Apr 30 '14 at 07:45
  • As I wrote above, [numbers are *converted* to 32-bit ints when used with bitwise operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators). Numbers which cannot retain their original value when converted to 32-bit ints are not considered integers according to `Number.isInteger`. Any hand-rolled solution should also not consider such numbers to be integers. The value we've added here is in debunking incorrect solutions. You're welcome. – Dagg Nabbit Apr 30 '14 at 23:36
  • Integer doesn't mean "a certain kind of variable" here, since types are loose. Integer means "a float with zero fractional part". In bitwise operations, you have limitations but that's completely offtopic here. The question clearly aimed one thing, you're talking about another; a special case that is probably irrelevant. It doesn't help. – dkellner May 01 '14 at 00:52
  • Maybe you're right. Taking a closer look at `Number.isInteger`, it's capped at +/- 2^53, so it does consider numbers outside the range of 32-bit ints to also be integers (but does not consider numbers that are big/small enough to lose precision -- "unsafe integers" -- as integers). In my experience, when people talk about integers in JavaScript, they are talking about numbers that can be expressed as 32-bit unsigned ints, since all parts of the language where integers matter use this format. Maybe the OP was talking about something different, who knows (but then the question is trivial). – Dagg Nabbit May 01 '14 at 02:03
  • I was surprised too, it really seemed trivial - but I think the asker didn't know that ints are floats in js. Bitwise operations with big numbers are quite uncommon, at least I rarely use them. In other languages I've always seen 32-bit ints called "integer" so I see your point; but as for js, I simply never tried how far the precision goes. I just supposed it's way beyond 32 bits and trusted all numbers to be addition-safe. – dkellner May 01 '14 at 09:14
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.

Mike Mancini
  • 59
  • 1
  • 1
5

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.

Arman
  • 5,136
  • 3
  • 34
  • 36
5
!!(24%1) // false
!!(24.2%1) // true
5
var isInt = function (n) { return n === (n | 0); };

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

ankr
  • 647
  • 6
  • 15
  • hey sorry why this returns false? console.log(isInt(7932938942839482938)); – itsme Feb 08 '14 at 16:33
  • 4
    Because that's exceeding MaxInt. – ankr Feb 10 '14 at 11:23
  • but you can set an Int max length nope? what if i dunno the int length is returned? – itsme Feb 10 '14 at 11:38
  • I'm not sure what you are asking, but you can read more about numbers here http://ecma262-5.com/ELS5_HTML.htm#Section_8.5. For handling big ints you could look into a library like https://github.com/jtobey/javascript-bignum – ankr Feb 10 '14 at 12:55
  • This code fails for integers that are less than Number.MAX_SAFE_INTEGER, but greater than 2^32. :-( – Kris Jenkins Feb 02 '15 at 13:39
  • 1
    @ekussberg Yes because `2` is an integer and `23` is considered a second argument to the function. In javascript decimals are written using dot as separator - so it should be `2.23`. – ankr Jan 27 '16 at 13:45
  • 1
    Or it's a great opportunity to learn about bitwise operations. You will gain a lot of benefit from that going forward. – ankr Dec 12 '17 at 14:04
5

Trying some of the answers here I ended up writing this solution. This works also with numbers inside a string.

function isInt(number) {
    if(!/^["|']{0,1}[-]{0,1}\d{0,}(\.{0,1}\d+)["|']{0,1}$/.test(number)) return false;
    return !(number - parseInt(number));
}

function isFloat(number) {
    if(!/^["|']{0,1}[-]{0,1}\d{0,}(\.{0,1}\d+)["|']{0,1}$/.test(number)) return false;
    return number - parseInt(number) ? true : false;
}

    var tests = {
        'integer' : 1,
        'float' : 1.1,
        'integerInString' : '5',
        'floatInString' : '5.5',
        'negativeInt' : -345,
        'negativeFloat' : -34.98,
        'negativeIntString' : '-45',
        'negativeFloatString' : '-23.09',
        'notValidFalse' : false,
        'notValidTrue' : true,
        'notValidString' : '45lorem',
        'notValidStringFloat' : '4.5lorem',
        'notValidNan' : NaN,
        'notValidObj' : {},
        'notValidArr' : [1,2],
    };

    function isInt(number) {
        if(!/^["|']{0,1}[-]{0,1}\d{0,}(\.{0,1}\d+)["|']{0,1}$/.test(number)) return false;
        return !(number - parseInt(number));
    }
    
    function isFloat(number) {
        if(!/^["|']{0,1}[-]{0,1}\d{0,}(\.{0,1}\d+)["|']{0,1}$/.test(number)) return false;
        return number - parseInt(number) ? true : false;
    }

    function testFunctions(obj) {
        var keys = Object.keys(obj);
        var values = Object.values(obj);

        values.forEach(function(element, index){
            console.log(`Is ${keys[index]} (${element}) var an integer? ${isInt(element)}`);
            console.log(`Is ${keys[index]} (${element}) var a float? ${isFloat(element)}`);
        });
    }

    testFunctions(tests);
4

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

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

gblazex
  • 49,155
  • 12
  • 98
  • 91
3

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:

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) }
SpYk3HH
  • 22,272
  • 11
  • 70
  • 81
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');
}
Vitim.us
  • 20,746
  • 15
  • 92
  • 109
2

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>
Zeromus
  • 4,472
  • 8
  • 32
  • 40
2

try this

let n;
return (n = value % 1) !== 0 && !isNaN(n);

when the return value is false means the input value is float number or float string, otherwise the input value is integer numbef or integer string.

basically it needs to check the precision value for not equal to zero.

another one is to check the correct string number also.

Dharman
  • 30,962
  • 25
  • 85
  • 135
OO7
  • 660
  • 4
  • 10
  • Review: Welcome to Stack Overflow! While your answer might technically be correct, I'm failing to see how it is substantially different from other answers here. Therefore I'm voting to delete it in this case. – timur Dec 26 '19 at 12:27
2
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') );
ibsanju
  • 21
  • 1
  • 4
  • I don't understand the design philosophy here. There's no need to use lambdas at all. You're also doing many redundant calculations. There are 48 other answers here. What distinguishes this one from the others? – General Grievance Feb 24 '22 at 01:05
2

THIS IS FINAL CODE FOR CHECK BOTH INT AND 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;   
}   
Ken Le
  • 1,787
  • 2
  • 22
  • 34
2

Compare that floor() result is not the same as ceil() result.

const isFloat = v => !isNaN(v) && Math.floor(v) !== Math.ceil(v);
> isFloat(1)
= false

> isFloat(1.1)
= true

> isFloat(42)
= false

> isFloat(84.42)
= true
neki-krkan
  • 21
  • 2
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.

Punith Raj
  • 2,164
  • 3
  • 27
  • 45
1

For those curious, using Benchmark.js I tested the most up-voted answers (and the one posted today) on this post, here are my results:

var n = -10.4375892034758293405790;
var suite = new Benchmark.Suite;
suite
    // kennebec
    .add('0', function() {
        return n % 1 == 0;
    })
    // kennebec
    .add('1', function() {
        return typeof n === 'number' && n % 1 == 0;
    })
    // kennebec
    .add('2', function() {
        return typeof n === 'number' && parseFloat(n) == parseInt(n, 10) && !isNaN(n);
    })

    // Axle
    .add('3', function() {
        return n.toString().indexOf('.') === -1;
    })

    // Dagg Nabbit
    .add('4', function() {
        return n === +n && n === (n|0);
    })

    // warfares
    .add('5', function() {
        return parseInt(n) === n;
    })

    // Marcio Simao
    .add('6', function() {
        return /^-?[0-9]+$/.test(n.toString());
    })

    // Tal Liron
    .add('7', function() {
        if ((undefined === n) || (null === n)) {
            return false;
        }
        if (typeof n == 'number') {
            return true;
        }
        return !isNaN(n - 0);
    });

// Define logs and Run
suite.on('cycle', function(event) {
    console.log(String(event.target));
}).on('complete', function() {
    console.log('Fastest is ' + this.filter('fastest').pluck('name'));
}).run({ 'async': true });

0 x 12,832,357 ops/sec ±0.65% (90 runs sampled)
1 x 12,916,439 ops/sec ±0.62% (95 runs sampled)
2 x 2,776,583 ops/sec ±0.93% (92 runs sampled)
3 x 10,345,379 ops/sec ±0.49% (97 runs sampled)
4 x 53,766,106 ops/sec ±0.66% (93 runs sampled)
5 x 26,514,109 ops/sec ±2.72% (93 runs sampled)
6 x 10,146,270 ops/sec ±2.54% (90 runs sampled)
7 x 60,353,419 ops/sec ±0.35% (97 runs sampled)

Fastest is 7 Tal Liron
jnthnjns
  • 8,962
  • 4
  • 42
  • 65
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).

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().

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

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.

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):

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)...

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]

KeMBro2012
  • 19
  • 2
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.

Mirek Rusin
  • 18,820
  • 3
  • 43
  • 36
1

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

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

Zaur Nasibov
  • 22,280
  • 12
  • 56
  • 83
Chris West
  • 885
  • 8
  • 17
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.

if(object instanceof Number ){
   if( ((Number) object).doubleValue() % 1 == 0 ){
      //your object is an integer
   }
   else{
      //your object is a double
   }
}
toddsalpen
  • 411
  • 4
  • 9
1
try this one
function amountcheck()
    {
        var dpamt=$('#dpamt').val()/5000;
        var ints=dpamt.toString();
        var isint=ints.split('.');
        if(isint[1]>0)
        {
            alert('float value');
            return false;
        }
        else
        {   
            alert('int value');
        }
    }
Ashish4434
  • 118
  • 6
1

You can use the Number.isInteger() method to check if the number is an integer or a float by dividing them for example:

    function isNumberFloatOrInteger(a, b){
     if(Number.isInteger(a / b)){
      return true;
      }
      else{ return false };
}

Note: isInteger() is not compatible with internet explorer.

Kalana
  • 5,631
  • 7
  • 30
  • 51
Ashraf
  • 65
  • 1
  • 9
1

There is Number.isInteger(number) to check this. Doesn't work in Internet Explorer but that browser isn't used anymore. If you need string like "90" to be an integer (which wasnt the question) try Number.isInteger(Number(number)). The "official" isInteger considers 9.0 as an integer, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number. It looks like most answers are correct for older browsers but modern browsers have moved on and actually support float integer check.

user6830669
  • 161
  • 4
1

For Float

var decimal=  /^[-+]?[0-9]+\.[0-9]+$/; 

if (!price.match(decimal)) {
      alert('Please enter valid float');
      return false;
    }

For integer

var number = /^\d+$/; 

if (!price.match(number)) {
      alert('Please enter valid integer');
      return false;
    }
Rajesh N
  • 6,198
  • 2
  • 47
  • 58
1

With this you can check if a string or a number is "decimal" (float properly):

var IsDecimal = function(num){
    return ((num.toString().split('.').length) <= 2 && num.toString().match(/^[\+\-]?\d*\.?\d+(?:[Ee][\+\-]?\d+)?$/)) ? (!isNaN(Number.parseFloat(num))) : false ;
}

and this other works for check if a string or a number is Integer:

var IsInteger = function(num){
    return ((num.toString().split('.').length) == 1 && num.toString().match(/^[\-]?\d+$/)) ? (!isNaN(Number.parseInt(num))) : false ;
}

var IsDecimal = function(num){
    return ((num.toString().split('.').length) <= 2 && num.toString().match(/^[\+\-]?\d*\.?\d+(?:[Ee][\+\-]?\d+)?$/)) ? (!isNaN(Number.parseFloat(num))) : false ;
}

var IsInteger = function(num){
    return ((num.toString().split('.').length) == 1 && num.toString().match(/^[\-]?\d+$/)) ? (!isNaN(Number.parseInt(num))) : false ;
}


console.log("-------------- As string --------------");
console.log("Integers:");
console.log("0 = " + IsInteger("0"));
console.log("34 = " + IsInteger("34"));
console.log(".34 = " + IsInteger(".34"));
console.log("3.4 = " + IsInteger("3.4"));
console.log("3e = " + IsInteger("3e"));
console.log("e3 = " + IsInteger("e3"));
console.log("-34 = " + IsInteger("-34"));
console.log("--34 = " + IsInteger("--34"));
console.log("034 = " + IsInteger("034"));
console.log("0-34 = " + IsInteger("0-34"));
console.log("Floats/decimals:");
console.log("0 = " + IsDecimal("0"));
console.log("64 = " + IsDecimal("64"));
console.log(".64 = " + IsDecimal(".64"));
console.log("6.4 = " + IsDecimal("6.4"));
console.log("6e2 = " + IsDecimal("6e2"));
console.log("6e = " + IsDecimal("6e"));
console.log("e6 = " + IsDecimal("e6"));
console.log("-64 = " + IsDecimal("-64"));
console.log("--64 = " + IsDecimal("--64"));
console.log("064 = " + IsDecimal("064"));
console.log("0-64 = " + IsDecimal("0-64"));
console.log("\n-------------- As numbers --------------");
console.log("Integers:");
console.log("0 = " + IsInteger(0));
console.log("34 = " + IsInteger(34));
console.log(".34 = " + IsInteger(0.34));
console.log("3.4 = " + IsInteger(3.4));
console.log("-34 = " + IsInteger(-34));
console.log("034 = " + IsInteger(034));
console.log("0-34 = " + IsInteger(0-34));
console.log("Floats/decimals:");
console.log("0 = " + IsDecimal(0));
console.log("64 = " + IsDecimal(64));
console.log(".64 = " + IsDecimal(0.64));
console.log("6.4 = " + IsDecimal(6.4));
console.log("6e2 = " + IsDecimal(6e2));
console.log("-64 = " + IsDecimal(-64));
console.log("064 = " + IsDecimal(064));
console.log("0-64 = " + IsDecimal(0-64));
Carlos Guerra
  • 24
  • 1
  • 4
1

to check the number is Int or not and apply 2 decimal format, you can use the formula below in React-Native.

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

    show = (x) => {
        if(x) {
           if (this.isInt(x)) {
               return ${x} 
           }
           else {
            return ${x.toFixed(2)}
           }
        }
    }
M Mahmud Hasan
  • 1,303
  • 1
  • 13
  • 20
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;
}
neoneye
  • 50,398
  • 25
  • 166
  • 151
1

I'm late to the party but here is my version

isInteger: obj => Number.isInteger(!isNaN(obj % 1) && obj % 1 !== 0 ? obj : parseInt(obj)),
ONYX
  • 5,679
  • 15
  • 83
  • 146
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.

Community
  • 1
  • 1
XMight
  • 1,991
  • 2
  • 20
  • 36
0

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;
}
Axle
  • 1,807
  • 2
  • 14
  • 18
0

This is mine:

function isInt(quale) {
    var valore = $('#'+quale).val().toLowerCase();
    if (isNaN(Number(String(valore))) || (valore.indexOf("e") > 0)) {
        // Not int
    } else {
        // Is Int!
    }
}

And this:

function isFloat(quale) {
   var valore = $('#'+quale).val();
   valore = valore.replace(",", "");
   if (isNaN(String(valore)) || (valore.indexOf("e") > 0)) {
    // Not Float
   } else {
    // Float
   }
}

Ad majora!

Damy Z
  • 11
0

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.

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;

};
Michael Ryan Soileau
  • 1,763
  • 17
  • 28
0

Condtion for floating validation :

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

Condtion for Integer validation :

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

Hope this might be helpful.

Joe Mike
  • 1,150
  • 1
  • 9
  • 16
0

The functions below guard against empty strings,undefines,nulls, and max/min value ranges. The Javascript engine should have built in these functions from day one. :)

Enjoy!

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
}
wanglabs
  • 57
  • 4
0

I needed to check an input value if it's integer or float and to do that I've come up with the following:

function isInteger(x) {
  var integer = parseInt(x, 10);
  if (!isNaN(integer) && !isFloat(x)) {
    return true;
  }
  return false;
}

function isFloat(x) {
  var f = parseFloat(x);
  var floor = Math.floor(f);
  var fraction = f - floor;
  if (fraction > 0) {
    return true;
  }
  return false;
}

var cases = [
  "1",
  "1.00",
  "1.01",
  "0.05",
  "ab1",
  "ab1.1",
  1,
  1.00,
  1.01,
  0.05,
  1e+5,
  "",
  true,
  false,
  null,
  NaN,
  undefined,
];

console.log("isInteger()");
for (var i = 0; i < cases.length; i++) {
  console.log(cases[i], isInteger(cases[i]));
}

console.log("\nisFloat()");
for (var i = 0; i < cases.length; i++) {
  console.log(cases[i], isFloat(cases[i]));
}
akinuri
  • 10,690
  • 10
  • 65
  • 102
0

I find this the most elegant way:

function isInteger(n) {
    return n === (n^0);
}

It cares also to return false in case of a non-numeric value.

bugovicsb
  • 422
  • 1
  • 7
  • 15
  • 1
    dude, "Bitwise operators treat their operands as a sequence of 32 bits", your function can not handling big number – anru Jun 14 '17 at 23:18
0

I know there are 30 answers already, but one complicated way is to do this:

function isInteger(n) {
    return n.toString().split('.').length === 1;
}

Explanation: We first convert n to a string, and split it based on a dot. If n is a floating point, like 4.5, then split will return an array ['4', '5']. If it is an integer like 45, it will return ['45']. Therefore, if the length of the array is 1, then we know it is a number.

P.S. If you want to write this function in the new ES6 format (arrow functions):

const isInteger = n => n.toString().split('.').length === 1;
theProCoder
  • 390
  • 6
  • 21
0

This is the best solution I can come up for float and interger number checking.

function isFloat(n) {
  if (!n) {
    return false
  }
  return !isNaN(n % 1) && n % 1 !== 0;
}

function isInt(n) {
  if (n.length==0) {
    return false
  }
  return !isNaN(n % 1) && n % 1 == 0;
}
zernab hussain
  • 339
  • 3
  • 6
-2
parseInt(yourNumber)=== parseFloat(yourNumber)
Code Lღver
  • 15,573
  • 16
  • 56
  • 75
Hatem
  • 19