How do I check that a number is float or integer?

837,053

Solution 1

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.

Solution 2

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

Solution 3

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

Solution 4

Why not something like this:

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

Solution 5

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!

Share:
837,053
coure2011
Author by

coure2011

Updated on February 17, 2022

Comments

  • coure2011
    coure2011 about 2 years

    How to find that a number is float or integer?

    1.25 --> float  
    1 --> integer  
    0 --> integer  
    0.25 --> float
    
  • Dagg Nabbit
    Dagg Nabbit over 13 years
    Might want to check that the value is numeric... isFloat('abc') returns true
  • Claudiu
    Claudiu over 13 years
    heh awesom exploit, it's pretty much mine (n===+n to check for numeric, n|0 to round), but with built-in operators. funky
  • Pointy
    Pointy over 13 years
    @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.
  • John Hartsock
    John Hartsock over 13 years
    @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)
  • Dagg Nabbit
    Dagg Nabbit over 13 years
    @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
    Dagg Nabbit over 13 years
    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.
  • woods
    woods over 12 years
    I think your first implementation is brilliant and efficient and the second redundant. Right?
  • djd
    djd about 12 years
    @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.
  • Pointy
    Pointy about 12 years
    @Dave yes that's true, but note that when JavaScript wants to deal with integers it usually bashes them down to 32 bits.
  • VLostBoy
    VLostBoy about 12 years
    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.
  • SimonSimCity
    SimonSimCity about 12 years
    Thanks, even if JavaScript does not differ between float and int, this is extremely useful for translation: unicode.org/repos/cldr-tmp/trunk/diff/supplemental/…
  • GajendraSinghParihar
    GajendraSinghParihar over 11 years
    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 jsbin.com/elohuq/1/edit
  • Jason Grout
    Jason Grout about 11 years
    This function fails on the empty string: isNumber('') is true.
  • hacklikecrack
    hacklikecrack almost 11 years
    isFloat("So. I'm a float then?");
  • hacklikecrack
    hacklikecrack almost 11 years
    This only tests for float if n happens to be a number
  • acdcjunior
    acdcjunior almost 11 years
    +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.
  • Imran-UK
    Imran-UK almost 11 years
    This is actually the core of a good solution for me. I needed to allow positive integers and disallow floats, strings and negative integers.
  • TachyonVortex
    TachyonVortex almost 11 years
    +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.
  • ina
    ina almost 11 years
    Why the use of === vs == ?
  • whoblitz
    whoblitz over 10 years
    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).
  • Dan
    Dan over 10 years
    @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.
  • Claudiu
    Claudiu over 10 years
    @Dan: ===+ is actually two operators, === (strict equality), and then unary +, e.g. (+5). the | is bit-wise or, yes.
  • Dagg Nabbit
    Dagg Nabbit over 10 years
    @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.
  • Frank Fang
    Frank Fang over 10 years
    isInt(1.000000000000000000000000001) === true
  • itsme
    itsme over 10 years
    hey sorry why this returns false? console.log(isInt(7932938942839482938));
  • ankr
    ankr over 10 years
    Because that's exceeding MaxInt.
  • itsme
    itsme over 10 years
    but you can set an Int max length nope? what if i dunno the int length is returned?
  • ankr
    ankr over 10 years
    I'm not sure what you are asking, but you can read more about numbers here ecma262-5.com/ELS5_HTML.htm#Section_8.5. For handling big ints you could look into a library like github.com/jtobey/javascript-bignum
  • tothemario
    tothemario about 10 years
    Perfect to test simple unsigned integers.
  • tothemario
    tothemario about 10 years
    One liner: /^[0-9]+$/.test(String(value))
  • js1568
    js1568 about 10 years
    isFloat("°º¤ø,¸¸,ø¤º°°º¤ø,I'm floating.¸,ø¤°º¤ø,¸¸,ø¤º°°º¤ø,")
  • Gaston Sanchez
    Gaston Sanchez about 10 years
    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.
  • skeggse
    skeggse about 10 years
    Shorter and slightly less readable one-liner: /^[0-9]+$/.test(''+value)
  • Chris Bartley
    Chris Bartley about 10 years
    Doesn't handle negative integers. You don't need the ternary operator either since test() returns a boolean. This should do it: return /^-?\d+$/.test(String(value));
  • Marcio Mazzucato
    Marcio Mazzucato about 10 years
    @ChrisBartley, Thanks! I made an update, including your credits. Please check if everything is okay now.
  • Dagg Nabbit
    Dagg Nabbit about 10 years
    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.
  • dkellner
    dkellner about 10 years
    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.
  • Dagg Nabbit
    Dagg Nabbit about 10 years
    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.
  • dkellner
    dkellner about 10 years
    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
    dkellner about 10 years
    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.
  • Dagg Nabbit
    Dagg Nabbit about 10 years
    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.
  • dkellner
    dkellner about 10 years
    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.
  • Dagg Nabbit
    Dagg Nabbit about 10 years
    As I wrote above, numbers are converted to 32-bit ints when used with 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.
  • dkellner
    dkellner about 10 years
    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.
  • Dagg Nabbit
    Dagg Nabbit about 10 years
    @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
    Dagg Nabbit about 10 years
    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).
  • dkellner
    dkellner about 10 years
    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.
  • sbichenko
    sbichenko about 10 years
    This seems like a vastly better solution than the others in this thread. Could the community offer some criticism, perhaps?
  • shime
    shime about 10 years
    isFloat(NaN) // true
  • Claudiu
    Claudiu about 10 years
    @shime: Good catch. NaN is technically a floating point number though... depends what the use case is I suppose.
  • whoughton
    whoughton almost 10 years
    var y = 1.00; y === parseInt(y, 10); // this returns true for me, which is not really what we want.
  • Skylar Saveland
    Skylar Saveland over 9 years
    Worst answer on SO? null % 1 === 0, [] % 1 === 0
  • kennebec
    kennebec over 9 years
    The question was how to check if a number is an integer, not how to check any value.
  • Dukeatcoding
    Dukeatcoding over 9 years
    This works in my Chrome now too and probably the way to go in the future
  • Dukeatcoding
    Dukeatcoding over 9 years
    would you still use it or go for the new Number.isInteger() ?
  • Maarten Bodewes
    Maarten Bodewes over 9 years
    An integer isn't a float? News to me.
  • andrewrk
    andrewrk over 9 years
    it's not wrong. 1.000000000000000000000000001 === 1
  • stef
    stef over 9 years
    Wrong for reasons described above. It validates an empty input field as containing an integer.
  • Onur Yıldırım
    Onur Yıldırım over 9 years
    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!
  • Dagg Nabbit
    Dagg Nabbit over 9 years
    @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.
  • Onur Yıldırım
    Onur Yıldırım over 9 years
    @DaggNabbit well, isInteger(-1000) will return true which is not an unsigned integer.
  • Dagg Nabbit
    Dagg Nabbit over 9 years
    @OnurYıldırım doh, I meant signed.
  • Kris Jenkins
    Kris Jenkins over 9 years
    This code fails for integers that are less than Number.MAX_SAFE_INTEGER, but greater than 2^32. :-(
  • tsh
    tsh over 9 years
    Note that second isInt may got false with isInt(new Number(0)).
  • Mirek Rusin
    Mirek Rusin about 9 years
    n === +n is redundant in integer test, no?
  • dotty
    dotty about 9 years
    4ff returns true. Is that expected?
  • JimmyMcHoover
    JimmyMcHoover almost 9 years
    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.
  • JGV
    JGV almost 9 years
    does not work for me. n === Number(n) always fail and returns false.
  • M Miller
    M Miller almost 9 years
    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.
  • F Lekschas
    F Lekschas almost 9 years
    Seems like 1.0 is rejected as a float: 1.0 === +1.0 && 1.0 !== (1.0|0) >>> false.
  • Automatico
    Automatico over 8 years
    In my opinion the best solution.
  • Alexander
    Alexander over 8 years
    It does not work with using ===. At least, in Firefox. But it DOES work, if to use ==.
  • Tomáš Zato
    Tomáš Zato over 8 years
    Funny occasion when this doesn't work is when you use Number.
  • RhinoDevel
    RhinoDevel over 8 years
    The only "downside" I see is that the given number n is converted to a string by parseInt. See MDN. But I will use this solution. :)
  • Tadas T
    Tadas T over 8 years
    isFloat(1.0) => false
  • Rocco
    Rocco over 8 years
    This is only 1/2 the answer. Question clearly says float or integer.
  • AdrianCooney
    AdrianCooney over 8 years
    The question asked how to check if a number is a float or an integer, not arbitrary string input.
  • user3787706
    user3787706 over 8 years
    why is that a downside? it's just converted for comparison
  • django
    django over 8 years
    isFloat(12.0) is false .. ?
  • django
    django over 8 years
    isFloat(12.0) is false
  • django
    django over 8 years
    isInteger(12.0) is true
  • ekussberg
    ekussberg over 8 years
    isInt(1,02) - returns true, but should return false
  • Marcio Mazzucato
    Marcio Mazzucato over 8 years
    @Rocco, I talked about the is_float() function, so i think the answer is complete
  • ankr
    ankr over 8 years
    @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.
  • Flimzy
    Flimzy about 8 years
    @ekussberg: Why should that return false? 1 is an int. and 02, the second argument, is ignored.
  • Jim
    Jim almost 8 years
    I like this one because it's a short, simple answer that doesn't rely on cryptic bitwise operations.
  • Admin
    Admin almost 8 years
    @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.
  • tsh
    tsh over 7 years
    try isFloat(123456789012345678901234567890); And your function will return true, since the number is converted to '1.2345678901234568e+29' which contains a dot sign.
  • tsh
    tsh over 7 years
    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.
  • Admin
    Admin over 7 years
    Apparently, floats that end with .0 are automatically cast to Int in JavaScript.
  • Sergei Panfilov
    Sergei Panfilov over 7 years
    Number.isInteger(12.0) //true (Chrome, Feb '17)
  • Sergei Panfilov
    Sergei Panfilov over 7 years
    Good approach IMHO
  • Axle
    Axle over 7 years
    I would add that the ES6 method includes() makes this answer even simpler
  • Francesco Pasa
    Francesco Pasa about 7 years
    This with the polyfill is the most reliable and simple solution.
  • Milan
    Milan almost 7 years
    dude, "Bitwise operators treat their operands as a sequence of 32 bits", your function can not handling big number
  • Lukas Liesis
    Lukas Liesis almost 7 years
    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
    Lukas Liesis almost 7 years
    failed with 1.2. Always test numeric functions with 0.1 0.2 0.3
  • Константин Ван
    Константин Ван over 6 years
    @SergeyPanfilov 12.0 ∈ ℤ.
  • doubleOrt
    doubleOrt over 6 years
    @LukasLiesis not for me.
  • doubleOrt
    doubleOrt over 6 years
    There is no need for any of the strict equality operators here.
  • doubleOrt
    doubleOrt over 6 years
    Why parseFloat ?
  • ankr
    ankr over 6 years
    Or it's a great opportunity to learn about bitwise operations. You will gain a lot of benefit from that going forward.
  • Krishnadas PC
    Krishnadas PC over 6 years
    Regex will be always slower than other methods.
  • Rohmer
    Rohmer over 6 years
    !!(24.0%1) is false
  • nunocastromartins
    nunocastromartins about 6 years
    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 and isSafeInteger.
  • luckyguy73
    luckyguy73 about 6 years
    pretty sure that is modulus % and not dividing /
  • Shashank K
    Shashank K about 6 years
    This fails if input type is string. Eg: If n="750" it returns false.
  • vpibano
    vpibano about 5 years
    THIS is what I am looking for! I used this one like this for my project. Perfect!
  • timur
    timur over 4 years
    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.
  • wchargin
    wchargin over 4 years
    −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.
  • Aalex Gabi
    Aalex Gabi over 4 years
    isFloat(1563457121531) returns false
  • fabpico
    fabpico about 4 years
    Try console.log(isFloat(1.0)); results false.
  • piecioshka
    piecioshka over 3 years
    isFloat(NaN) and isFloat(Infinity) returns true :/
  • GwenM
    GwenM almost 3 years
    @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.
  • Quentin
    Quentin over 2 years
    This claims that 0 is not an integer.
  • zernab hussain
    zernab hussain over 2 years
    I updated an integer null condition. it will not return false on zero now. Thanks for correction.
  • General Grievance
    General Grievance about 2 years
    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?