Thought leadership from the most innovative tech companies, all in one place.

How to Get the Number of Digits of a Number with JavaScript

A tutorial on getting the number of digits of a number with JavaScript.

Sometimes, we want to get the number of digits of a number with JavaScript.

In this article, we’ll look at how to get the number of digits of a number with JavaScript.

Use the Number.prototype.toString Method

We can get the number of digits of a non-negative integer with the Number.prototype.toString method.

For instance, we can write:

const getLength = (number) => {
  return number.toString().length;
};
console.log(getLength(12345));

to get the number of digits of 12345.

To do that, we create the getLength function that takes the number parameter.

And we return the length of the string form of number.

Therefore, the console log should log 5 since 12345 has 5 digits.

Get the Number of Digits of Decimal Numbers

We can’t use toString to get the number of digits of decimal numbers since it just returns the string form of the number, including all the decimal digits and other characters that come with the number.

To get the number of digits of a decimal number, we can use math methods.

For instance, we can write:

const getLength = (number) => {
  return Math.max(Math.floor(Math.log10(Math.abs(number))), 0) + 1;
};
console.log(getLength(12345.67));

To get the number of digits of number by taking the log with 10 of it and then adding 1 to get the number of digits of it.

We have to make sure number is converted to a positive number with Math.abs so we can take the log of it.

Next, we call Math.floor to take the floor of the log to get the number of digits excluding the leftmost digit.

Then we get the floor of the log and 0 with Math.max and add 1 to get the number of digits.

Therefore, the console log should log 5 since we use the log operation to discard the decimal digits.

Conclusion

We can use math methods or convert a number to a string to get the number of digits of a JavaScript number.




Continue Learning