使用 JavaScript 获取位数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14879691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 18:12:22  来源:igfitidea点击:

Get number of digits with JavaScript

javascriptcountdigits

提问by bit4fox

As the title of my post suggests, I would like to know how many digits var numberhas. For example: If number = 15;my function should return 2. Currently, it looks like this:

正如我的帖子标题所暗示的那样,我想知道有多少个数字var number。例如:如果number = 15;我的函数应该返回2. 目前,它看起来像这样:

function getlength(number) {
  return number.toString().length();
}

But Safari says it is not working due to a TypeError:

但 Safari 表示它无法正常工作,因为TypeError

'2' is not a function (evaluating 'number.toString().length()')

As you can see, '2'is actually the right solution. But why is it not a function?

如您所见,'2'实际上是正确的解决方案。但这是为什么呢not a function

回答by VisioN

lengthis a property, not a method. You can't call it, hence you don't need parenthesis ():

length是一个属性,而不是一个方法。你不能调用它,因此你不需要括号()

function getlength(number) {
    return number.toString().length;
}

UPDATE:As discussed in the comments, the above example won't work for float numbers. To make it working we can either get rid of a period with String(number).replace('.', '').length, or count the digits with regular expression: String(number).match(/\d/g).length.

更新:正如评论中所讨论的,上面的例子不适用于浮点数。为了让它工作,我们可以用 去掉句号String(number).replace('.', '').length,或者用正则表达式计算数字:String(number).match(/\d/g).length

In terms of speed potentially the fastest way to get number of digits in the given number is to do it mathematically. For positive integersthere is a wonderful algorithm with log10:

就速度而言,获取给定数字中位数的最快方法可能是数学上的。对于正整数,有一个很棒的算法log10

var length = Math.log(number) * Math.LOG10E + 1 | 0;  // for positive integers

For all types of integers (including negatives) there is a brilliant optimised solution from @Mwr247, but be careful with using Math.log10, as it is not supported by many legacy browsers. So replacing Math.log10(x)with Math.log(x) * Math.LOG10Ewill solve the compatibility problem.

对于所有类型的整数(包括负数),@Mwr247 提供了一个出色的优化解决方案,但使用时要小心Math.log10,因为许多旧浏览器不支持它。所以替换Math.log10(x)withMath.log(x) * Math.LOG10E将解决兼容性问题。

Creating fast mathematical solutions for decimal numbers won't be easy due to well known behaviour of floating point math, so cast-to-string approach will be more easy and fool proof. As mentioned by @streetlogicsfast casting can be done with simple number to string concatenation, leading the replacesolution to be transformed to:

由于浮点数学的众所周知的行为,为十进制数创建快速数学解决方案并不容易,因此强制转换为字符串的方法将更加容易和万无一失。正如@streetlogics所提到的,快速转换可以通过简单的数字到字符串连接来完成,从而将替换解决方案转换为:

var length = (number + '').replace('.', '').length;  // for floats

回答by Mwr247

Here's a mathematical answer (also works for negative numbers):

这是一个数学答案(也适用于负数):

function numDigits(x) {
  return Math.max(Math.floor(Math.log10(Math.abs(x))), 0) + 1;
}

And an optimized version of the above (more efficient bitwise operations):

以及上述的优化版本(更高效的按位运算):

function numDigits(x) {
  return (Math.log10((x ^ (x >> 31)) - (x >> 31)) | 0) + 1;
}

Essentially, we start by getting the absolute value of the input to allow negatives values to work correctly. Then we run the through the log10 operation to give us what power of 10 the input is (if you were working in another base, you would use the logarithm for that base), which is the number of digits. Then we floor the output to only grab the integer part of that. Finally, we use the max function to fix decimal values (any fractional value between 0 and 1 just returns 1, instead of a negative number), and add 1 to the final output to get the count.

本质上,我们首先获取输入的绝对值以允许负值正常工作。然后我们运行 log10 操作来给我们输入的 10 的幂(如果你在另一个基数中工作,你会使用那个基数的对数),这是数字的数量。然后我们将输出地板只抓取其中的整数部分。最后,我们使用 max 函数来固定十进制值(0 到 1 之间的任何小数值只返回 1,而不是负数),并在最终输出中加 1 以得到计数。

The above assumes (based on your example input) that you wish to count the number of digits in integers (so 12345 = 5, and thus 12345.678 = 5 as well). If you would like to count the total number of digits in the value (so 12345.678 = 8), then add this before the 'return' in either function above:

以上假设(基于您的示例输入)您希望计算整数位数(因此 12345 = 5,因此 12345.678 = 5 也是如此)。如果您想计算值中的总位数(因此 12345.678 = 8),请在上述任一函数中的“返回”之前添加它:

x = Number(String(x).replace(/[^0-9]/g, ''));

回答by streetlogics

Since this came up on a Google search for "javascript get number of digits", I wanted to throw it out there that there is a shorter alternative to this that relies on internal casting to be done for you:

由于这是在 Google 搜索“javascript 获取数字位数”时出现的,因此我想把它扔出去,有一个更短的替代方案,它依赖于为您完成的内部转换:

var int_number = 254;
var int_length = (''+int_number).length;

var dec_number = 2.12;
var dec_length = (''+dec_number).length;

console.log(int_length, dec_length);

Yields

产量

3 4

回答by user40521

var i = 1;
while( ( n /= 10 ) >= 1 ){ i++ }

23432          i = 1
 2343.2        i = 2
  234.32       i = 3
   23.432      i = 4
    2.3432     i = 5
    0.23432

回答by Maciej Maciej

If you need digits (after separator), you can simply split number and count length second part (after point).

如果您需要数字(分隔符后),您可以简单地拆分数字并计算第二部分的长度(点后)。

function countDigits(number) {
    var sp = (number + '').split('.');
    if (sp[1] !== undefined) {
        return sp[1].length;
    } else {
        return 0;
    }
}

回答by BloodyLogic

Note :This function will ignorethe numbers after the decimal mean dot, If you wanna count with decimal then remove the Math.floor(). Direct to the point check this out!

注:此功能将忽略小数点后的平均数字,如果你想用十进制计数然后取出Math.floor()。直接点看这个!

function digitCount ( num )
{
     return Math.floor( num.toString()).length;
}

 digitCount(2343) ;

// ES5+

// ES5+

 const digitCount2 = num => String( Math.floor( Math.abs(num) ) ).length;

 console.log(digitCount2(3343))

BasicallyWhat's going on here. toString()and String()same build-in function for converting digit to string, once we converted then we'll find the length of the string by build-in function length.

基本上这里发生了什么。toString()String()用于将数字转换为字符串的相同内置函数,一旦我们转换,我们将通过内置函数找到字符串的长度length

Alert:But this function wouldn't work properly for negative number, if you're trying to play with negative number then check this answerOr simple put Math.abs()in it;

警告:但是这个函数对于负数不能正常工作,如果你想玩负数,那么检查这个答案或者简单地Math.abs()输入它;

Cheer You!

加油你!

回答by A P

it would be simple to get the length as

获得长度很简单

  `${NUM}`.length

where NUM is the number to get the length for

其中 NUM 是获取长度的数字

回答by Nate

I'm still kind of learning Javascript but I came up with this function in C awhile ago, which uses math and a while loop rather than a string so I re-wrote it for Javascript. Maybe this could be done recursively somehow but I still haven't really grasped the concept :( This is the best I could come up with. I'm not sure how large of numbers it works with, it worked when I put in a hundred digits.

我仍在学习 Javascript,但我不久前在 C 中想出了这个函数,它使用数学和 while 循环而不是字符串,所以我为 Javascript 重新编写了它。也许这可以以某种方式递归完成,但我仍然没有真正掌握这个概念:(这是我能想到的最好的方法。我不确定它适用于多大的数字,当我输入一百时它起作用了数字。

function count_digits(n) {
    numDigits = 0;
    integers = Math.abs(n);

    while (integers > 0) {
        integers = (integers - integers % 10) / 10;
        numDigits++;
    }
    return numDigits;
}

edit: only works with integer values

编辑:仅适用于整数值

回答by Rafael Melón

Two digits: simple function in case you need two or more digits of a number with ECMAScript 6 (ES6):

两位数:如果您需要使用 ECMAScript 6 (ES6) 的两位或更多位数字的简单功能:

const zeroDigit = num => num.toString().length === 1 ? `0${num}` : num;

回答by Yogesh Aggarwal

Problem statement: Count number/string not using string.length()jsfunction. Solution: we could do this through the Forloop. e.g

问题陈述:不使用 string.length()jsfunction计算数字/字符串。解决方案:我们可以通过 Forloop 来做到这一点。例如

for (x=0; y>=1 ; y=y/=10){
  x++;
}

if (x <= 10) {
  this.y = this.number;                
}   

else{
  this.number = this.y;
}    

}

}