Get the number of digits after the Decimal in JavaScript

avatar

Borislav Hadzhiev

Sat Oct 23 20211 min read

banner

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

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee