Categories

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

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 comes 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 add 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.

## By John Au-Yeung

Web developer specializing in React, Vue, and front end development.