Get the number of digits before the Decimal in JavaScript

avatar

Borislav Hadzhiev

Mon Oct 25 20212 min read

banner

Photo by Blake Wisz

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 #

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