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

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


var x = 1234567;

x.toString().length;

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


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

var num = 123;

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

or

alert(num.toString().length);

首先将其转换为字符串:

var mynumber = 123;
alert((""+mynumber).length);

添加一个空字符串将隐式地导致mynumber变成一个字符串。


试试这个:

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

它在使用中的例子


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

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/


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

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

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

ES2015更新

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

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

我想纠正@Neal的答案,这对整数来说很好,但在前一种情况下,数字1将返回0的长度。

function Longueur(numberlen)
{
    var length = 0, i; //define `i` with `var` as not to clutter the global scope
    numberlen = parseInt(numberlen);
    for(i = numberlen; i >= 1; i)
    {
        ++length;
        i = Math.floor(i/10);
    }
    return length;
}

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

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.

我一直在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 num = 123;
alert(num.toString().length);

性能一(ie11中性能最好)

var num = 123;
alert((num + '').length);

数学(在Chrome和firefox中表现最好,但在ie11中最慢)

var num = 123
alert(Math.floor( Math.log(num) / Math.LN10 ) + 1)

这里有一个jspref http://jsperf.com/fastest-way-to-get-the-first-in-a-number/2


你应该使用最简单的字符串(stringLength),可读性总是胜过速度。但如果你关心速度,下面有一些。

三种不同的方法,速度各不相同。

// 34ms
let weissteinLength = function(n) { 
    return (Math.log(Math.abs(n)+1) * 0.43429448190325176 | 0) + 1;
}

// 350ms
let stringLength = function(n) {
    return n.toString().length;
}

// 58ms
let mathLength = function(n) {
    return Math.ceil(Math.log(n + 1) / Math.LN10);
}

// Simple tests below if you care about performance.

let iterations = 1000000;
let maxSize = 10000;

// ------ Weisstein length.

console.log("Starting weissteinLength length.");
let startTime = Date.now();

for (let index = 0; index < iterations; index++) {
    weissteinLength(Math.random() * maxSize);
}

console.log("Ended weissteinLength length. Took : " + (Date.now() - startTime ) + "ms");


// ------- String length slowest.

console.log("Starting string length.");
startTime = Date.now();

for (let index = 0; index < iterations; index++) {
    stringLength(Math.random() * maxSize);
}

console.log("Ended string length. Took : " + (Date.now() - startTime ) + "ms");


// ------- Math length.

console.log("Starting math length.");
startTime = Date.now();

for (let index = 0; index < iterations; index++) {
    mathLength(Math.random() * maxSize);
}

也可以使用模板字符串:

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

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

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

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()。


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

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);

I'm perplex about converting into a string the given number because such an algorithm won't be robust and will be prone to errors: it will show all its limitations especially in case it has to evaluate very long numbers. In fact before converting the long number into a string it will "collapse" into its exponential notation equivalent (example: 1.2345e4). This notation will be converted into a string and this resulting string will be evaluated for returning its length. All of this will give a wrong result. So I suggest not to use that approach.

看看下面的代码,并运行代码片段来比较不同的行为:

let num = 116234567891011121415113441236542134465236441625344625344625623456723423523429798771121411511034412365421344652364416253446253446254461253446221314623879235441623683749283441136232514654296853446323214617456789101112141511344122354416236837492834411362325146542968534463232146172368374928344113623251465429685; let lenFromMath; let lenFromString; // The suggested way: lenFromMath = Math.ceil(Math.log10(num + 1)); // this works in fact returns 309 // The discouraged way: lenFromString = String(num).split("").length; // this doesn't work in fact returns 23 /*It is also possible to modify the prototype of the primitive "Number" (but some programmer might suggest this is not a good practice). But this is will also work:*/ Number.prototype.lenght = () => {return Math.ceil(Math.log10(num + 1));} lenFromPrototype = num.lenght(); console.log({lenFromMath, lenFromPrototype, lenFromString});


为了获得任何由小数部分和小数部分分开的数字的相关位数(如果前导小数部分为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 x = 1234567;
String(x).length;

它比. tostring()(在接受的答案中)短。