功能错误确定数字中的位数

时间:2011-08-23 06:01:43

标签: javascript html

我有一个简单的javascript函数,告诉我一个数字中有多少位数。

我的问题:在最后一行,我收到编译错误,上面写着“Missing last'”'parenthisis'。我正在改变我通过谷歌和发现的一个片段。它使用函数Math.log10(),但我不确定这样的函数是否存在?

你能帮我确定一个数字中的位数(例如1000 = 4,10 = 2等)吗?

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

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

2 个答案:

答案 0 :(得分:4)

您无法在Javascript中转换为int。相反,请使用Math.floor。此外,除以Math.log(10)(或Math.LN10),而不是使用Math.log10()来查找数字的基数10对数。:

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

答案 1 :(得分:1)

你可以试试这个:
假设“数字”是正整数值

function getDigitCount(number)
{
   var c = "x" + number;
   return c.length -1;
}
相关问题