How do I check that a number is float or integer?
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!
coure2011
Updated on February 17, 2022Comments
-
coure2011 about 2 years
How to find that a number is
float
orinteger
?1.25 --> float 1 --> integer 0 --> integer 0.25 --> float
-
Dagg Nabbit over 13 yearsMight want to check that the value is numeric...
isFloat('abc')
returnstrue
-
Claudiu over 13 yearsheh awesom exploit, it's pretty much mine (
n===+n
to check for numeric,n|0
to round), but with built-in operators. funky -
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 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 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 over 13 yearsCareful, 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 over 12 yearsI think your first implementation is brilliant and efficient and the second redundant. Right?
-
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 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 about 12 yearsJust 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 about 12 yearsThanks, 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 over 11 yearsNice trick but not the correct answer as it fails to check empty string
""
and1.0
isInt("");
&&isInt(1.0);
both result intrue
see this demo jsbin.com/elohuq/1/edit -
Jason Grout about 11 yearsThis function fails on the empty string: isNumber('') is true.
-
hacklikecrack almost 11 yearsisFloat("So. I'm a float then?");
-
hacklikecrack almost 11 yearsThis only tests for float if n happens to be a number
-
acdcjunior almost 11 years+1 This is good.
isInt('1')
returnstrue
as expected (at least for me). Weird enough, though, this returnstrue
toisInt([5])
as well. Didn't matter for me, but may for you, so, take care. -
Imran-UK almost 11 yearsThis is actually the core of a good solution for me. I needed to allow positive integers and disallow floats, strings and negative integers.
-
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 almost 11 yearsWhy the use of === vs == ?
-
whoblitz over 10 yearsIna, 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 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 over 10 years@Dan:
===+
is actually two operators,===
(strict equality), and then unary+
, e.g.(+5)
. the|
is bit-wise or, yes. -
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 over 10 yearsisInt(1.000000000000000000000000001) === true
-
itsme over 10 yearshey sorry why this returns false? console.log(isInt(7932938942839482938));
-
ankr over 10 yearsBecause that's exceeding MaxInt.
-
itsme over 10 yearsbut you can set an Int max length nope? what if i dunno the int length is returned?
-
ankr over 10 yearsI'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 about 10 yearsPerfect to test simple unsigned integers.
-
tothemario about 10 yearsOne liner:
/^[0-9]+$/.test(String(value))
-
js1568 about 10 yearsisFloat("°º¤ø,¸¸,ø¤º°°º¤ø,I'm floating.¸,ø¤°º¤ø,¸¸,ø¤º°°º¤ø,")
-
Gaston Sanchez about 10 yearsThe 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 about 10 yearsShorter and slightly less readable one-liner:
/^[0-9]+$/.test(''+value)
-
Chris Bartley about 10 yearsDoesn'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 about 10 years@ChrisBartley, Thanks! I made an update, including your credits. Please check if everything is okay now.
-
Dagg Nabbit about 10 yearsThis 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 about 10 yearsMmmmmmm... 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 about 10 yearsWhat 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 about 10 yearsSomething 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 about 10 yearsIt'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 about 10 yearsNumbers 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 isn === (n | 0)
as shown in another answer. -
dkellner about 10 yearsI 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 about 10 yearsAs 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 about 10 yearsInteger 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 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 about 10 yearsMaybe 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 about 10 yearsI 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 about 10 yearsThis seems like a vastly better solution than the others in this thread. Could the community offer some criticism, perhaps?
-
shime about 10 years
isFloat(NaN) // true
-
Claudiu about 10 years@shime: Good catch. NaN is technically a floating point number though... depends what the use case is I suppose.
-
whoughton almost 10 yearsvar y = 1.00; y === parseInt(y, 10); // this returns true for me, which is not really what we want.
-
Skylar Saveland over 9 yearsWorst answer on SO?
null % 1 === 0
,[] % 1 === 0
-
kennebec over 9 yearsThe question was how to check if a number is an integer, not how to check any value.
-
Dukeatcoding over 9 yearsThis works in my Chrome now too and probably the way to go in the future
-
Dukeatcoding over 9 yearswould you still use it or go for the new Number.isInteger() ?
-
Maarten Bodewes over 9 yearsAn integer isn't a float? News to me.
-
andrewrk over 9 yearsit's not wrong. 1.000000000000000000000000001 === 1
-
stef over 9 yearsWrong for reasons described above. It validates an empty input field as containing an integer.
-
Onur Yıldırım over 9 yearsin 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 returnfalse
which is wrong! -
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 over 9 years@DaggNabbit well,
isInteger(-1000)
will returntrue
which is not an unsigned integer. -
Dagg Nabbit over 9 years@OnurYıldırım doh, I meant signed.
-
Kris Jenkins over 9 yearsThis code fails for integers that are less than Number.MAX_SAFE_INTEGER, but greater than 2^32. :-(
-
tsh over 9 yearsNote that second
isInt
may gotfalse
withisInt(new Number(0))
. -
Mirek Rusin about 9 years
n === +n
is redundant in integer test, no? -
dotty about 9 years
4ff
returns true. Is that expected? -
JimmyMcHoover almost 9 yearsMay i ask why you use
Number(n) === n
and nottypeof n === "number"
? I guess it depends on the intention what you use, but the first also is true ifn === "5"
, for example. -
JGV almost 9 yearsdoes not work for me. n === Number(n) always fail and returns false.
-
M Miller almost 9 yearsA 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 almost 9 yearsSeems like
1.0
is rejected as a float:1.0 === +1.0 && 1.0 !== (1.0|0)
>>>false
. -
Automatico over 8 yearsIn my opinion the best solution.
-
Alexander over 8 yearsIt does not work with using ===. At least, in Firefox. But it DOES work, if to use ==.
-
Tomáš Zato over 8 yearsFunny occasion when this doesn't work is when you use
Number
. -
RhinoDevel over 8 yearsThe only "downside" I see is that the given number
n
is converted to a string byparseInt
. See MDN. But I will use this solution. :) -
Tadas T over 8 yearsisFloat(1.0) => false
-
Rocco over 8 yearsThis is only 1/2 the answer. Question clearly says
float
orinteger
. -
AdrianCooney over 8 yearsThe question asked how to check if a number is a float or an integer, not arbitrary string input.
-
user3787706 over 8 yearswhy is that a downside? it's just converted for comparison
-
django over 8 yearsisFloat(12.0) is false .. ?
-
django over 8 yearsisFloat(12.0) is false
-
django over 8 yearsisInteger(12.0) is true
-
ekussberg over 8 yearsisInt(1,02) - returns true, but should return false
-
Marcio Mazzucato over 8 years@Rocco, I talked about the is_float() function, so i think the answer is complete
-
ankr over 8 years@ekussberg Yes because
2
is an integer and23
is considered a second argument to the function. In javascript decimals are written using dot as separator - so it should be2.23
. -
Flimzy about 8 years@ekussberg: Why should that return false? 1 is an int. and 02, the second argument, is ignored.
-
Jim almost 8 yearsI like this one because it's a short, simple answer that doesn't rely on cryptic bitwise operations.
-
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 was1.02
, it would be false as expected.,
is an operator in JavaScript. -
tsh over 7 yearstry
isFloat(123456789012345678901234567890)
; And your function will returntrue
, since the number is converted to'1.2345678901234568e+29'
which contains a dot sign. -
tsh over 7 yearsWhat 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 got1
instead of1e100
which will fail in your solution. -
Admin over 7 yearsApparently, floats that end with .0 are automatically cast to Int in JavaScript.
-
Sergei Panfilov over 7 years
Number.isInteger(12.0) //true
(Chrome, Feb '17) -
Sergei Panfilov over 7 yearsGood approach IMHO
-
Axle over 7 yearsI would add that the ES6 method includes() makes this answer even simpler
-
Francesco Pasa about 7 yearsThis with the polyfill is the most reliable and simple solution.
-
Milan almost 7 yearsdude, "Bitwise operators treat their operands as a sequence of 32 bits", your function can not handling big number
-
Lukas Liesis almost 7 yearsThis 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 almost 7 yearsfailed with
1.2
. Always test numeric functions with 0.1 0.2 0.3 -
Константин Ван over 6 years@SergeyPanfilov
12.0 ∈ ℤ
. -
doubleOrt over 6 years@LukasLiesis not for me.
-
doubleOrt over 6 yearsThere is no need for any of the strict equality operators here.
-
doubleOrt over 6 yearsWhy
parseFloat
? -
ankr over 6 yearsOr it's a great opportunity to learn about bitwise operations. You will gain a lot of benefit from that going forward.
-
Krishnadas PC over 6 yearsRegex will be always slower than other methods.
-
Rohmer over 6 years
!!(24.0%1)
is false -
nunocastromartins about 6 yearsI'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 forNumber.isSafeInteger
.Number.isInteger
should not check whether the number is a "safe integer". See on MDN: isInteger and isSafeInteger. -
luckyguy73 about 6 yearspretty sure that is modulus % and not dividing /
-
Shashank K about 6 yearsThis fails if input type is string. Eg: If n="750" it returns false.
-
vpibano about 5 yearsTHIS is what I am looking for! I used this one like this for my project. Perfect!
-
timur over 4 yearsReview: 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 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 over 4 yearsisFloat(1563457121531) returns false
-
fabpico about 4 yearsTry
console.log(isFloat(1.0));
results false. -
piecioshka over 3 years
isFloat(NaN)
andisFloat(Infinity)
returns true :/ -
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 over 2 yearsThis claims that
0
is not an integer. -
zernab hussain over 2 yearsI updated an integer null condition. it will not return false on zero now. Thanks for correction.
-
General Grievance about 2 yearsI 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?