Get the number of digits before the Decimal in JavaScript

avatar

Borislav Hadzhiev

Last updated: Oct 25, 2021

banner

Photo from Unsplash

Get the number of digits before the Decimal #

To get the number of digits before the decimal:

  1. Check if the number is an integer, if it is, the number of digits is 1.
  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 0.
index.js
function beforeDecimal(num) { if (Number.isInteger(num)) { return 1; } return num.toString().split('.')[0].length; } console.log(beforeDecimal(1)); // 👉️ 1 console.log(beforeDecimal(13.23)); // 👉️ 2 console.log(beforeDecimal(134.23)); // 👉️ 3

We created a reusable function that returns the number of digits before 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 return that it has 1 digit before the decimal. This is entirely use case dependent and you might want to return 0 if this scenario.

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

index.js
console.log(Number.isInteger(3)); // 👉️ true console.log(Number.isInteger(-3)); // 👉️ true console.log(Number.isInteger(3.0)); // 👉️ true console.log(Number.isInteger(3.3)); // 👉️ false console.log(Number.isInteger('3')); // 👉️ false

Note that numbers like 3.00 are considered integers because 3.00 is the same as 3.

index.js
console.log(3.00 === 3); // 👉️ true

After we find out the number is not an integer, we convert it to a string and 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('3.14'.split('.')); // 👉️ ['3', '14'] console.log('16.24'.split('.')); // 👉️ ['16', '24'] console.log('1.24'.split('.')); // 👉️ ['1', '24']

The last step is to access the length property on the array element at index 0 because it stores the digits before the decimal.

Indexes are zero-based in JavaScript, meaning the first array element has an index of 0 and the last - an index of array.length - 1.

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.