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

485,893

Solution 1

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

Solution 2

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.

Solution 3

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

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

Solution 4

Simple, but effective!

Math.floor(number) === number;

Solution 5

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 )
}
Share:
485,893
Björn
Author by

Björn

Updated on August 11, 2021

Comments

  • Björn
    Björn almost 3 years

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