473

I am looking for an easy way in JavaScript to check if a number has a decimal place in it (in order to determine if it is an integer). For instance,

23 -> OK
5 -> OK
3.5 -> not OK
34.345 -> not OK
if(number is integer) {...}
reformed
  • 4,505
  • 11
  • 62
  • 88
Björn
  • 12,587
  • 12
  • 51
  • 70

24 Answers24

1201

Using modulus will work:

num % 1 != 0
// 23 % 1 = 0
// 23.5 % 1 = 0.5

Note that this is based on the numerical value of the number, regardless of format. It treats numerical strings containing whole numbers with a fixed decimal point the same as integers:

'10.0' % 1; // returns 0
10 % 1; // returns 0
'10.5' % 1; // returns 0.5
10.5 % 1; // returns 0.5
user56reinstatemonica8
  • 32,576
  • 21
  • 101
  • 125
Andy E
  • 338,112
  • 86
  • 474
  • 445
  • possibly != 0, for negative values – Jimmy Feb 20 '10 at 22:51
  • @Jimmy: true, I didn't account for negative input :-) Updated. – Andy E Feb 20 '10 at 22:53
  • 16
    I didn't down vote but I'd say its something to do with 20.0, still has a decimal point and satisfies the above. +1 from me anyway for teaching me something new :) – Abe Petrillo Sep 01 '11 at 16:53
  • 7
    @Abe: true enough, though I think that's unlikely. It's impossible to say if `20.0` has a decimal point programmatically, unless it is expressed as a string. Also, none of the other solutions got a down vote for not tackling that ;-) – Andy E Sep 01 '11 at 16:58
  • 1
    @SREEP: see comments above. 0.00 isn't 0.00 in JavaScript when represented as a number value. It can be represented as a string ("0.00"), in which case the question for that is *"check if a string is a whole number"* instead of *"check if a number is a whole number"*. – Andy E Aug 15 '13 at 16:23
  • 1
    This will not be valid incase the input is "10." – Swanidhi Dec 05 '14 at 13:49
  • 3
    @Swanidhi: what do you mean? What won't be valid? `"10."` is a whole number and the result will be exactly the same as `"10"` or `10`. – Andy E Dec 05 '14 at 16:56
  • I was building a calculator field and I had to know the position of a cursor within the number, and the decimal was removed and then replaced, so I had to know if the cursor was before or after the decimal. I had to treat the number as a string to do this successfully. Perhaps an edge case, but a relevant one. – Jason Jun 26 '15 at 14:42
  • 5
    The OP asks about checking if a **NUMBER** is a whole number. He nowhere mentions **strings** - in that regards, Andy's answer is right. – Om Shankar May 02 '16 at 00:20
  • I would argue there are use cases for detecting if a number has a decimal of 0 (1.0 vs 1) not just for strings. I have some numerical input boxes that I want to test if the user entered a decimal or not. No strings involved here, but I still want to know if the user enters '10.0' vs '10'. – Confused May 25 '16 at 18:57
  • @Confused: see the above comments for how JavaScript does not keep the floating point representation for .0 numbers. You're in luck for your use case, though, as `input.value` returns a string even for number inputs (as opposed to `input.valueAsNumber`). – Andy E May 26 '16 at 08:18
  • 1
    12333333333333333333333321312312312313.5444 it is not working for this digit. is the reason i used this value in var – Bachas Sep 22 '17 at 06:49
  • What about NaN? Seems to be valid – Jake Rowsell Feb 13 '19 at 15:35
  • @JakeRowsell I'm not sure I understand. `NaN % 1` gives `NaN`. – Andy E Feb 14 '19 at 16:06
  • This works in certain situations, and I am generally hesitant to contradict a solution that functions. However it's a messy enough solution that it likely causes more problems than it solves. There are simpler ways to solve this problem. – Mira Welner Jun 26 '19 at 04:24
  • @MiraWelner Simpler than a modulo? I think not.. If you think it's messy just wrap it within a named function.. – Tofandel Aug 30 '20 at 16:10
  • @Bachas This is due to javascript's maximum number precision, if you type 1233333331312313.544 in your console you'll see that it's 1233333331312313.5 add another digit and you get an integer – Tofandel Aug 30 '20 at 16:14
  • definitely downvote this... doesnt try to address the issue that OP is having – tnkh Nov 04 '20 at 08:00
  • Number(num % 1 != 0) – Samnad Sainulabdeen Aug 18 '22 at 09:08
147
Number.isInteger(23);  // true
Number.isInteger(1.5); // false
Number.isInteger("x"); // false: 

Number.isInteger() is part of the ES6 standard and not supported in IE11.

It returns false for NaN, Infinity and non-numeric arguments while x % 1 != 0 returns true.

le_m
  • 19,302
  • 9
  • 64
  • 74
  • 8
    solution fails for 12.0 – Vikas Arora May 21 '18 at 09:01
  • 3
    @VikasArora No, it works as intended. `Number.isInteger(12.0)` returns `true`. – le_m May 21 '18 at 19:59
  • This seems like it should be the right answer, but unfortunately, it doesn't work for scientific notation, e.g. `Number.isInteger('1e3')` is `false`, even though `Number.isInteger(1e3)` is true. Assuming the intent of the question is to find non-integer values (rather than the actual presence of a decimal point in the representation), then the string value '12.0' _should_ pass as it represents an integer, but again, `Number.isInteger('12.0')` is `false`. – brianmearns Apr 19 '19 at 15:48
  • 1
    @brianmearns OP's question is whether a `number` is whole or not. If your input is a string, you need to convert it into a `number` first e.g. via `parseFloat()`, of course. – le_m Apr 22 '19 at 11:43
  • 2
    This won't work if there are too many decimal places: `Number.isInteger(2.000000000000000000001)` // true – dYale Mar 22 '21 at 18:36
  • 6
    @dYale This is because `2.000000000000000000001 === 2` in JavaScript – le_m Mar 22 '21 at 21:44
71

Or you could just use this to find out if it is NOT a decimal:

string.indexOf(".") == -1;
dYale
  • 1,541
  • 1
  • 16
  • 19
Ike
  • 753
  • 5
  • 2
  • 3
    I think this one is the actual solution as this this working even for XX.0 – Deepankar Sarkar Dec 20 '14 at 13:36
  • this method works if you have an string, but the question ask for an integer value. – alvarodoune Jul 10 '15 at 18:09
  • 11
    convert to string before proceed.. ie: `yournumber.toString.indexOf(".")` – Daniel Omine Sep 21 '15 at 05:43
  • 1
    francisco_ssb.. the point symbol is universal... represents the decimal place in math language.. this is universal and should work in any country. If you talking about commas (","), you must convert to point (".") before the indexOf("."), obviously.. – Daniel Omine Sep 21 '15 at 07:18
  • 1
    I think when he meant it doesn't work in some countries, he's referring to currency, as the Euro uses a comma instead of a decimal point. However, the question isn't specific to currency, just decimals... as in a fraction of a number. – AuRise Apr 13 '16 at 14:21
  • 3
    This doesn't work if decimal is 1.00 and you want it to be an int unless you coerce value – simon-p-r Jun 15 '16 at 10:12
  • 1
    @simon-p-r how don't work with 1.00? 1.00 has a decimal place and satisfy the condition, totally works, am I missing something? – ncubica Feb 26 '17 at 19:22
  • 1
    The original question is a little unclear, but the intent _seems to me_ to be determining whether or not the number if a whole number (vis: "in order to determine if it is an integer", and "`if(number is integer)`"). If that's the true intent, then 1.00 should pass despite the decimal point in that particular string encoding of the value. – brianmearns Apr 19 '19 at 15:44
  • This will fail for 1.0 which is a whole number. Additionally, conversion to string and search operation is obviously more expensive then basic arithmetic operation. – SJ00 Dec 28 '19 at 18:12
  • @brianmearns 1.00 does pass correctly if you are working with a number `(1.00).toString().indexOf('.') == -1 //true` if you are working with a string just `parseFloat` before `parseFloat("1.00").toString().indexOf('.') == -1 //true` – Tofandel Aug 30 '20 at 16:05
  • this fails for .0 – Deen John Mar 01 '22 at 16:43
33

Simple, but effective!

Math.floor(number) === number;
dYale
  • 1,541
  • 1
  • 16
  • 19
24

The most common solution is to strip the integer portion of the number and compare it to zero like so:

function Test()
{
     var startVal = 123.456
     alert( (startVal - Math.floor(startVal)) != 0 )
}
Thomas
  • 63,911
  • 12
  • 95
  • 141
  • 38
    Why not just `startVal != Math.floor(startVal)`? – Andy E Feb 21 '10 at 10:39
  • 4
    Nice. Same concept, but your version is even cleaner. – Thomas Feb 21 '10 at 15:56
  • 1
    @Andy E: This is possible only for positive numbers. It won't work for negative numbers.. – Seeya K Apr 25 '13 at 04:27
  • 3
    @SeeyaK: of course it will work for negative numbers. Please feel free to try it. – Andy E Apr 25 '13 at 07:44
  • not working with long string like 893144042145698745.3 please check – Deepak Goyal May 22 '15 at 07:14
  • 1
    @DeepakGoyal - That is by design. The `Math.Floor` function takes a decimal value and the largest decimal value allowed in JavaScript is `2^53 - 1` or `9007199254740991`. Since `893144042145698745.3` is larger than this maximum, the function will fail. – Thomas May 26 '15 at 18:02
  • 1
    @Thomas so any solution for this problem – Deepak Goyal May 28 '15 at 05:58
  • 2
    @DeepakGoyal - The problem to which you refer is related to handling very large numbers in JavaScript. I suspect you'd have to get a library that uses bit manipulation and arrays to handle values larger than JavaScript's largest number. Of course, the other choice is not to do this in JavaScript but instead pass the value to a server side component where you use a language or library that can handle very large values. – Thomas May 29 '15 at 15:05
  • 1
    to be more consistent, regarding of negative numbers, just do *1 before proceed. – Daniel Omine Sep 21 '15 at 05:44
  • This solution is so simple and beautiful! – viery365 May 10 '18 at 00:36
  • fails for `e` notation – prgmrDev Apr 03 '19 at 05:08
24
Number.isSafeInteger(value);

In JavaScript, isSafeInteger() is a Number method that is used to return a Boolean value indicating whether a value is a safe integer. This means that it is an integer value that can be exactly represented as an IEEE-754 double precision number without rounding.

aaditya
  • 555
  • 7
  • 19
19

//How about byte-ing it?

Number.prototype.isInt= function(){
 return this== this>> 0;
}

I always feel kind of bad for bit operators in javascript-

they hardly get any exercise.

kennebec
  • 102,654
  • 32
  • 106
  • 127
14

Number.isInteger() is probably the most concise. It returns true if it is an integer, and false if it isn't.

Jean-François Corbett
  • 37,420
  • 30
  • 139
  • 188
Mira Welner
  • 409
  • 4
  • 15
  • 1
    This should be the accepted answer, because it is better then using modulus due to the string issues. – Ini Sep 06 '18 at 00:02
  • 1
    modulus operator is smart mathematically, this is smart programaticaly, it's always simpler to use a function that already exists (specially if it's in the std) – Jaacko Torus Oct 24 '20 at 05:03
  • IE doesn't support this. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger – Howdy Sep 21 '21 at 03:33
  • 1
    IE doesn't support a lot of things though/j – Mira Welner Oct 10 '21 at 03:06
6
number = 20.5

if (number == Math.floor(number)) {

alert("Integer")

} else {

alert("Decimal")

}

Pretty cool and works for things like XX.0 too! It works because Math.floor() chops off any decimal if it has one so if the floor is different from the original number we know it is a decimal! And no string conversions :)

4
var re=/^-?[0-9]+$/;
var num=10;
re.test(num);
ghostdog74
  • 327,991
  • 56
  • 259
  • 343
4

convert number string to array, split by decimal point. Then, if the array has only one value, that means no decimal in string.

if(!number.split(".")[1]){
    //do stuff
}

This way you can also know what the integer and decimal actually are. a more advanced example would be.

number_to_array = string.split(".");
inte = number_to_array[0];
dece = number_to_array[1]; 

if(!dece){
    //do stuff
}
Kareem
  • 5,068
  • 44
  • 38
3
function isDecimal(n){
    if(n == "")
        return false;

    var strCheck = "0123456789";
    var i;

    for(i in n){
        if(strCheck.indexOf(n[i]) == -1)
            return false;
    }
    return true;
}
Sirko
  • 72,589
  • 19
  • 149
  • 183
Vitor Lins
  • 31
  • 1
3
parseInt(num) === num

when passed a number, parseInt() just returns the number as int:

parseInt(3.3) === 3.3 // false because 3 !== 3.3
parseInt(3) === 3     // true
Michael
  • 22,196
  • 33
  • 132
  • 187
  • 6
    I like this one a lot, but depends on one's specific needs. Unfortunately, I need a function to FAIL the test `parseInt(3.0) === 3.0 // true` – zipzit Feb 02 '15 at 23:24
2

Use following if value is string (e.g. from <input):

Math.floor(value).toString() !== value

I add .toString() to floor to make it work also for cases when value == "1." (ends with decimal separator or another string). Also Math.floor always returns some value so .toString() never fails.

michal.jakubeczy
  • 8,221
  • 1
  • 59
  • 63
1

Here's an excerpt from my guard library (inspired by Effective JavaScript by David Herman):

var guard = {

    guard: function(x) {
        if (!this.test(x)) {
            throw new TypeError("expected " + this);
        }
    }

    // ...
};

// ...

var number = Object.create(guard);
number.test = function(x) {
    return typeof x === "number" || x instanceof Number;
};
number.toString = function() {
    return "number";
};


var uint32 = Object.create(guard);
uint32.test = function(x) {
    return typeof x === "number" && x === (x >>> 0);
};
uint32.toString = function() {
    return "uint32";
};


var decimal = Object.create(guard);
decimal.test = function(x) {
    return number.test(x) && !uint32.test(x);
};
decimal.toString = function() {
    return "decimal";
};


uint32.guard(1234);     // fine
uint32.guard(123.4);    // TypeError: expected uint32

decimal.guard(1234);    // TypeError: expected decimal
decimal.guard(123.4);   // fine
schirrmacher
  • 2,341
  • 2
  • 27
  • 29
1

You can multiply it by 10 and then do a "modulo" operation/divison with 10, and check if result of that two operations is zero. Result of that two operations will give you first digit after the decimal point. If result is equal to zero then the number is a whole number.

if ( (int)(number * 10.0) % 10 == 0 ){
// your code
}
BSevo
  • 743
  • 5
  • 13
1
function isDecimal(num) {
  return (num !== parseInt(num, 10));
}
Steve Brush
  • 2,911
  • 1
  • 23
  • 15
1

You can use the bitwise operations that do not change the value (^ 0 or ~~) to discard the decimal part, which can be used for rounding. After rounding the number, it is compared to the original value:

function isDecimal(num) {
  return (num ^ 0) !== num;
}

console.log( isDecimal(1) ); // false
console.log( isDecimal(1.5) ); // true
console.log( isDecimal(-0.5) ); // true
makovkastar
  • 5,000
  • 2
  • 30
  • 50
1
function isWholeNumber(num) {
  return num === Math.round(num);
}
Dmitry Shashurov
  • 1,148
  • 13
  • 11
1

When using counters with decimal steps, checking if number is round will actually fail, as shown below. So it might be safest (although slow) to format the number with 9 (could be more) decimal places, and if it ends with 9 zeros, then it's a whole number.

const isRound = number => number.toFixed(9).endsWith('000000000');

for (let counter = 0; counter < 2; counter += 0.1) {
  console.log({ counter, modulo: counter % 1, formatted: counter.toFixed(9), isRound: isRound(counter) });
}
domaci_a_nas
  • 220
  • 2
  • 11
1

Using Number.isInteger(num) can help check what would count as whole number and what would not.

For example:

let num1 = 6.0000000000000001; // 16 decimal places
let num2 = 6.000000000000001; // 15 decimal places

Number.isInteger(num1); // true, because of loss of precision

// while:
Number.isInteger(num2); // false

So, in my opinion it's safe to use Number.isInteger() over other suggested ways if what you need is to know what is an integer mathematically.

Abdulsalam
  • 275
  • 4
  • 6
0

Perhaps this works for you?

It uses regex to check if there is a comma in the number, and if there is not, then it will add the comma and stripe.

var myNumber = '50';
function addCommaStripe(text){
    if(/,/.test(text) == false){
        return text += ',-';
    } else {
        return text;
    }
}
myNumber = addCommaStripe(myNumber);
Eugene Tiurin
  • 4,019
  • 4
  • 33
  • 32
  • Welcome to StackOverflow. Could you elaborate what this code does and why you think it will solve the problem. – quinz Jun 06 '19 at 11:26
  • @quinz It uses regex to check if there is a comma in the number, and if there is not then it will add the comma and stripe. So it does what the question is asking for with the added functionality of adding the formatting for rounded price tags. – user11608734 Jul 04 '19 at 11:04
  • jesus, regex is everywhere, I wanna kill myself, why did I become a developer. – Jaacko Torus Oct 24 '20 at 05:00
0

You can use this:

bool IsInteger() {
    if (num.indexOf(".") != -1) // a decimal
    {
        return Math.ceil(num) == Math.floor(num); // passes for 1.0 as integer if thats the intent.
    }
    return Number.isSafeInteger(num);
}

to check if the number is integer or decimal.

Gauravsa
  • 6,330
  • 2
  • 21
  • 30
-1

Function for check number is Decimal or whole number

function IsDecimalExist(p_decimalNumber) {
    var l_boolIsExist = true;

    if (p_decimalNumber % 1 == 0)
        l_boolIsExist = false;

    return l_boolIsExist;
}
Tom Sabel
  • 3,935
  • 33
  • 45
user1124
  • 9
  • 1