使用JavaScript获取位数 [英] Get number of digits with JavaScript

查看:234
本文介绍了使用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;
}

UPDATE:上面的例子不能用于浮点数。为了使它工作,我们可以用 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.log(x)* Math.LOG10E 替换 Math.log10(x)

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.

创建快速数学解的十进制数字并不容易众所周知的浮点数学行为,所以铸造到字符串的方法将更容易和愚蠢的证明。如 @streetlogics 所述,快速投射可以使用简单的数字到字符串连接,导致 replace 解决方案转换为:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆