使用 JavaScript 获取位数 [英] Get number of digits with JavaScript
问题描述
正如我帖子的标题所暗示的那样,我想知道 var number
有多少个数字.例如:如果 number = 15;
我的函数应该返回 2
.目前,它看起来像这样:
As the title of my post suggests, I would like to know how many digits var number
has. For example: If number = 15;
my function should return 2
. Currently, it looks like this:
function getlength(number) {
return number.toString().length();
}
但是 Safari 说由于 TypeError
无法正常工作:
But Safari says it is not working due to a TypeError
:
'2' is not a function (evaluating 'number.toString().length()')
如您所见,'2'
实际上是正确的解决方案.但为什么它不是函数
?
As you can see, '2'
is actually the right solution. But why is it not a function
?
推荐答案
length
是一个属性,而不是一个方法.你不能调用它,因此你不需要括号 ()
:
length
is a property, not a method. You can't call it, hence you don't need parenthesis ()
:
function getlength(number) {
return number.toString().length;
}
更新:正如评论中所讨论的,上面的示例不适用于浮点数.为了让它工作,我们可以用 String(number).replace('.', '').length
去掉句号,或者用正则表达式计算数字:String(number).match(/d/g).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
.
就速度而言,获取给定数字中位数的最快方法可能是数学计算.对于正整数,log10
有一个很棒的算法:
In terms of speed potentially the fastest way to get number of digits in the given number is to do it mathematically. For positive integers there is a wonderful algorithm with log10
:
var length = Math.log(number) * Math.LOG10E + 1 | 0; // for positive integers
对于所有类型的整数(包括负数),@Mwr247 有一个出色的优化解决方案,但要小心使用 Math.log10
,因为许多旧版浏览器不支持它.所以将 Math.log10(x)
替换为 Math.log(x) * Math.LOG10E
将解决兼容性问题.
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.LOG10E
will solve the compatibility problem.
由于众所周知的浮点数学行为,为十进制数创建快速数学解决方案并不容易,所以cast-to-string 方法将更容易和万无一失.正如 @streetlogics 所提到的,可以通过简单的数字到字符串的连接来完成快速转换,从而导致替换 要转换为的解决方案:
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 @streetlogics fast casting can be done with simple number to string concatenation, leading the replace solution to be transformed to:
var length = (number + '').replace('.', '').length; // for floats
这篇关于使用 JavaScript 获取位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!