Translate

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.

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)

One Response to “JavaScript: Get how many digits are there in a decimal number”

  1. don Says:

    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