开发者

Error in Function to Determine number of digits in a number

I have a simple javascript function that tells me how many digits 开发者_JS百科are in a number.

My Problem: On the last line I get a compiler error saying "Missing last ')' parenthisis". I am altering a snippet I found through google & it uses the function Math.log10() but I am not sure a function like this exists?

Can you help me to determine the number of digits in a number (eg 1000 = 4, 10 = 2, etc.)?

function getDigitCount( number )
{
    //return ((number ==0) ? 1 : (int)Math.log10(number) + 1);

    if ( (number == 0) )
    {
        return 1;
    }
    else return ((int)Math.log10(number) + 1);
}


You cannot cast to an int in Javascript. Instead, use Math.floor. Also, divide by Math.log(10) (or Math.LN10) instead of using Math.log10() to find the base 10 logarithm of a number.:

else return (Math.floor(Math.log(number)/Math.log(10)) + 1);


You may try this:
Assuming that "number" is a positive integer value

function getDigitCount(number)
{
   var c = "x" + number;
   return c.length -1;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜