Get the number of digits after the Decimal in JavaScript


Borislav Hadzhiev

Sat Oct 23 20211 min read


Photo by KaLisa Veer

Get the number of digits after the Decimal #

To get the number of digits after the decimal:

  1. Check if the number is an integer, if it is, the number of digits is 0.
  2. Otherwise, convert it to a string and use the split() method to split it on the dot.
  3. Access the length property on the array element at index 1.
function afterDecimal(num) { if (Number.isInteger(num)) { return 0; } return num.toString().split('.')[1].length; } console.log(afterDecimal(1)); // 👉️ 0 console.log(afterDecimal(1.0)); // 👉 0 console.log(afterDecimal(1.1)); // 👉️ 1 console.log(afterDecimal(1.123)); // 👉️ 3 console.log(afterDecimal(1.1234)); // 👉️ 4

We created a reusable function that returns the number of digits after the decimal.

We used the Number.isInteger method to determine if the passed in number is an integer.

If the number is an integer, we can conclude it has no digits after the decimal and return 0.

Here are some examples of using the Number.isInteger method.

console.log(Number.isInteger(1)); // 👉️ true console.log(Number.isInteger(-1)); // 👉️ true console.log(Number.isInteger(1.0)); // 👉️ true console.log(Number.isInteger(1.5)); // 👉️ false console.log(Number.isInteger('1')); // 👉️ false

Note that numbers like 1.00 are considered integers because 1.00 is the same as 1.

console.log(1.00 === 1); // 👉️ true

After we find out that the number is not an integer, we convert it to a string, so we can call the String.split method on it.

The split method takes a separator as a parameter and splits the string into an array of substrings.

console.log('1.15'.split('.')); // 👉️ ['1', '15'] console.log('1.157'.split('.')); // 👉️ ['1', '157'] console.log('1.1579'.split('.')); // 👉️ ['1', '1579']

The function returns the length of the second array element because it stores the digits after the decimal.

Further Reading #

Use the search field on my Home Page to filter through my more than 1,000 articles.