如何找到数字的长度

How can I find the length of a number?

本文关键字:数字 何找      更新时间:2023-09-26

我想在 JavaScript 或 jQuery 中获取数字的长度?

我已经尝试了value.length没有任何成功,我需要先将其转换为字符串吗?

var x = 1234567;
x.toString().length;

此过程也适用于Float NumberExponential number

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

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

这实际上给出了数字的"长度",即使它是指数形式。 num在这里应该是一个非负整数:如果它是负数,则取其绝对值,然后调整符号。

ES2015 更新

现在Math.log10是一回事,你可以简单地写

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

也可以使用模板字符串:

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

你必须把数字串起来才能取长度

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

alert(num.toString().length);

我一直在node.js中使用此功能,这是我迄今为止最快的实现:

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

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

以下参考应提供对该方法的一些见解:魏斯斯坦、埃里克·来自 MathWorld--A Wolfram Web 资源。

我相信一些按位操作可以取代 Math.abs,但 jsperf 表明 Math.abs 在大多数 js 引擎中运行良好。

更新:如评论中所述,此解决方案存在一些问题:(

Update2(解决方法):我相信在某些时候精度问题会出现,Math.log(...)*0.434...只是表现得出乎意料。但是,如果 Internet Explorer 或 Mobile 设备不是您的一杯茶,您可以将此操作替换为Math.log10函数。在 Node 中.js我用函数 nLength = (n) => 1 + Math.log10(Math.abs(n) + 1) | 0; 编写了一个快速的基本测试,Math.log10它按预期工作。请注意,Math.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)

这里有一个JSPREFhttp://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);
}

首先将其转换为字符串:

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

向其添加空字符串将隐式导致mynumber变成字符串。

好吧,如果不将整数转换为字符串,您可以制作一个时髦的循环:

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/

我在测试中被问到类似的问题。

在不转换为字符串的情况下查找数字的长度

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 x = 1234567;
String(x).length;

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

我对将给定的数字转换为字符串感到困惑,因为这样的算法不会很健壮并且容易出错:它将显示其所有限制,尤其是在它必须评估非常长的数字的情况下。事实上,在将长数转换为字符串之前,它将"折叠"为指数表示法等效(例如:1.2345e4)。此表示法将转换为字符串,并将计算此生成的字符串以返回其长度。所有这些都会给出错误的结果。所以我建议不要使用这种方法。

请查看以下代码并运行代码片段以比较不同的行为:

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

一种用于整数或整数部分长度而不平庸转换为string的方法:

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

更正@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;
}

要获取由整部分和小数部分分隔的任何数字的相关位数(如果前导小数部分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,
  };
}

试试这个:

$("#element").text().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.