我要在JavaScript或jQuery中获得一个数字的长度?

我尝试过价值。长度没有任何成功,我需要先将其转换为字符串吗?


当前回答

为了获得任何由小数部分和小数部分分开的数字的相关位数(如果前导小数部分为0,则整个部分的长度为0),我使用:

function getNumberLength(x) {
  let numberText = x.toString();
  let exp = 0;
  if (numberText.includes('e')) {
    const [coefficient, base] = numberText.split('e');
    exp = parseInt(base, 10);
    numberText = coefficient;
  }
  const [whole, decimal] = numberText.split('.');
  const wholeLength = whole === '0' ? 0 : whole.length;
  const decimalLength = decimal ? decimal.length : 0;
  return {
    whole: wholeLength > -exp ? wholeLength + exp : 0,
    decimal: decimalLength > exp ? decimalLength - exp : 0,
  };
}

其他回答

为了获得任何由小数部分和小数部分分开的数字的相关位数(如果前导小数部分为0,则整个部分的长度为0),我使用:

function getNumberLength(x) {
  let numberText = x.toString();
  let exp = 0;
  if (numberText.includes('e')) {
    const [coefficient, base] = numberText.split('e');
    exp = parseInt(base, 10);
    numberText = coefficient;
  }
  const [whole, decimal] = numberText.split('.');
  const wholeLength = whole === '0' ? 0 : whole.length;
  const decimalLength = decimal ? decimal.length : 0;
  return {
    whole: wholeLength > -exp ? wholeLength + exp : 0,
    decimal: decimalLength > exp ? decimalLength - exp : 0,
  };
}

我一直在node.js中使用这个功能,这是我目前为止最快的实现:

var nLength = function(n) { 
    return (Math.log(Math.abs(n)+1) * 0.43429448190325176 | 0) + 1; 
}

它应该处理正整数和负整数(也是指数形式),并应该以浮点数形式返回整数部分的长度。

下面的参考文献应该提供一些关于该方法的见解: Eric Weisstein;“数字长度。”来自MathWorld—Wolfram Web资源。

我相信一些位操作可以取代数学。但是jsperf显示Math. abs。Abs在大多数js引擎中工作得很好。

更新:正如评论中提到的,这个解决方案有一些问题:(

Update2(解决方案):我相信在某些时候精度问题开始出现,Math.log(…)*0.434…只是表现出人意料。但是,如果Internet Explorer或移动设备不是你的菜,你可以用Math代替这个操作。log10函数。在Node.js中,我写了一个快速的基本测试函数nLength = (n) => 1 + Math.log10(Math.abs(n) + 1) | 0;还有数学。Log10它像预期的那样工作。请注意数学。Log10不是普遍支持的。

是的,你需要转换为字符串,以找到长度。例如

var x=100;// type of x is number
var x=100+"";// now the type of x is string
document.write(x.length);//which would output 3.

也可以使用模板字符串:

const num = 123456
`${num}`.length // 6

好吧,有这么多答案,但这是一个纯粹的数学问题,只是为了好玩,或者为了记住数学很重要:

var len = Math.ceil(Math.log(num + 1) / Math.LN10);

这实际上给出了数字的“长度”,即使它是指数形式的。这里的Num应该是非负整数:如果它是负的,取它的绝对值,然后调整符号。

ES2015更新

现在是数学。Log10是一个东西,你可以简单地写出来

const len = Math.ceil(Math.log10(num + 1));