Get the number of digits after the Decimal in JavaScript

avatar

Borislav Hadzhiev

Last updated: Oct 23, 2021

banner

Photo from Unsplash

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.
index.js
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.

index.js
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.

index.js
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.

index.js
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 #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.