Sometimes, we want to find the length of a JavaScript number in our JavaScript app.
In this article, we’ll look at how to find the length of a JavaScript number.
Convert the Number to a String and Use the String’s length Property
One way to find the length of a JavaSdcript number is to convert the number to a string and then use the string’s length
property to get the number’s length.
For instance, we can write:
const x = 1234567;
console.log(x.toString().length);
We have the number x
.
Then we call toString
on it to convert it to a string.
And then we use the length
property to return its length.
Therefore, the console log should log 7.
Use the Math.ceil and Math.log Methods
We can get the logarithm of the number with base 10 to get the length of a number.
To do this, we cal use the Math.log
to get the natural log of the number.
Then we can divide the returned result by Math.LN10
to convert it to the log with base 10 of the same number.
And then we call Math.ceil
of that to round it up to the nearest integer to get the length.
For instance, we can write:
const x = 1234567;
const len = Math.ceil(Math.log(x + 1) / Math.LN10);
console.log(len);
to do all that.
We add 1 to x
to avoid taking the log of 0 when x
is 0.
Then we get that len
is 7.
Use the Math.ceil and Math.log10 Methods
ES6 comes with the Math.log10
method to get the log with base 10 of a number.
To use it, we write:
const x = 1234567;
const len = Math.ceil(Math.log10(x + 1));
console.log(len);
We call Math.log10
with x + 1
to avoid taking the log of 0 when x
is 0.
And we use Math.ceil
again to round the log up to the nearest integer.
And so we should get the same result as the other examples.
Conclusion
We can find the length of a number with various JavaScript math methods or convert it to a string and use the length
property.