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

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


当前回答

试试这个:

$("#element").text().length;

它在使用中的例子

其他回答

var x = 1234567;

x.toString().length;

这个过程也适用于浮点数和指数数。

为了求长度,你必须把数字变成字符串

var num = 123;

alert((num + "").length);

or

alert(num.toString().length);

在一次测试中,我也被问到类似的问题。

找到一个数字的长度而不转换为字符串

const numbers = [1, 10, 100, 12, 123, -1, -10, -100, -12, -123, 0, -0]

const numberLength = number => {

  let length = 0
  let n = Math.abs(number)

  do {
    n /=  10
    length++
  } while (n >= 1)

  return length
}

console.log(numbers.map(numberLength)) // [ 1, 2, 3, 2, 3, 1, 2, 3, 2, 3, 1, 1 ]

负数的添加使它更加复杂,因此Math.abs()。

也可以使用模板字符串:

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

为了获得任何由小数部分和小数部分分开的数字的相关位数(如果前导小数部分为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,
  };
}