Check if a number has a decimal place/is a whole number Check if a number has a decimal place/is a whole number javascript javascript

Check if a number has a decimal place/is a whole number


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 010 % 1; // returns 0'10.5' % 1; // returns 0.510.5 % 1; // returns 0.5


Number.isInteger(23);  // trueNumber.isInteger(1.5); // falseNumber.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.


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

string.indexOf(".") == -1;