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

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


当前回答

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

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.

其他回答

var x = 1234567;

x.toString().length;

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

试试这个:

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

它在使用中的例子

一种用于整数或整数部分长度的方法,无需将其常规转换为字符串:

var num = 9999999999; // your number
if (num < 0) num = -num; // this string for negative numbers
var length = 1;
while (num >= 10) {
   num /= 10;
   length++;
}
alert(length);

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

如果不把整数转换成字符串,你可以做一个奇怪的循环:

var number = 20000;
var length = 0;
for(i = number; i > 1; ++i){
     ++length;
     i = Math.floor(i/10);
}

alert(length);​

演示:http://jsfiddle.net/maniator/G8tQE/