JavaScript: Get how many digits are there in a decimal number

/**
 * 1 + Floor(LogBase10(number))
 * 
*/
function digits(n) { return 1+Math.floor(Math.log(n)/Math.log(10)); 
}

Yes, javascript doesn’t have a Math.log10() function.
I tried doing it by dividing by Math.ln10 constant but the function won’t return the correct number of digits when you pass numbers like 100,1000,10000,etc. So I just divided by Math.log(10) and it seems to work.

One thought on “JavaScript: Get how many digits are there in a decimal number

  1. I know your post is old, but I was looking for this and found the following is actually faster:

    function digits(n) { return ( n + “” ).length };

    It tends to run about 25% faster. (To see this do it in a loop 10000000 times or so)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.