我希望在javascript / jquery
中获取数字的长度我尝试value.length
但没有成功,我是否需要先将其转换为字符串?
答案 0 :(得分:227)
var x = 1234567;
x.toString().length;
此过程也适用于Float Number
和Exponential number
。
答案 1 :(得分:56)
好的,这么多的答案,但这是一个纯数学,只是为了乐趣或记住数学很重要:
var len = Math.ceil(Math.log(num + 1) / Math.LN10);
这实际上给出了数字的“长度”,即使它是指数形式。 num
在这里应该是一个非负整数:如果它是负数,则取其绝对值并在之后调整符号。
现在Math.log10
is a thing,你可以简单地写
const len = Math.ceil(Math.log10(num + 1));
答案 2 :(得分:11)
您必须将数字设为字符串才能占用长度
var num = 123;
alert((num + "").length);
或
alert(num.toString().length);
答案 3 :(得分:9)
我一直在node.js中使用这个功能,这是迄今为止我最快的实现:
var nLength = function(n) {
return (Math.log(Math.abs(n)+1) * 0.43429448190325176 | 0) + 1;
}
它应该处理正整数和负整数(也是指数形式)并且应该返回浮点数中整数部分的长度。
以下参考资料应提供有关该方法的一些见解: Weisstein, Eric W. "Number Length." From MathWorld--A Wolfram Web Resource.
我相信一些按位操作可以取代Math.abs,但是jsperf表明Math.abs在大多数js引擎中工作得很好。
更新:正如评论中所述,此解决方案有一些问题 :(
Update2(解决方法):我认为在某些时候精确问题会出现,而Math.log(...)*0.434...
只会出现意外情况。但是,如果Internet Explorer或移动设备不是您的茶,您可以使用Math.log10
功能替换此操作。在Node.js中,我使用函数nLength = (n) => 1 + Math.log10(Math.abs(n) + 1) | 0;
和Math.log10
编写了一个快速基本测试,它按预期工作。请注意,Math.log10
并非普遍支持。
答案 4 :(得分:5)
没有将整数转换为字符串,你可以做一个时髦的循环:
var number = 20000;
var length = 0;
for(i = number; i > 1; ++i){
++length;
i = Math.floor(i/10);
}
alert(length);
答案 5 :(得分:4)
首先将其转换为字符串:
var mynumber = 123;
alert((""+mynumber).length);
向其添加空字符串将隐式导致mynumber
变成字符串。
答案 6 :(得分:4)
有三种方法可以做到。
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
答案 7 :(得分:4)
还可以使用模板字符串:
const num = 123456
`${num}`.length // 6
答案 8 :(得分:2)
我想纠正@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;
}
答案 9 :(得分:1)
答案 10 :(得分:1)
三种不同的方法都具有变速速度。
// 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);
}
答案 11 :(得分:1)
我对将给定数字转换为字符串感到困惑,因为这样的算法不会健壮并且容易出错:它将显示其所有局限性,尤其是在必须评估非常长的数字的情况下。事实上,在将长数字转换为字符串之前,它会“折叠”为其指数表示法 等价物(例如: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});
答案 12 :(得分:0)
我在测试中被问到类似的问题。
查找数字长度而不转换为字符串
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()。
答案 13 :(得分:0)
一种不带整数的整数形式,无需转换为string
:
var num = 9999999999; // your number
var length = 1;
while (num >= 10) {
num /= 10;
length++;
}
alert(length);
答案 14 :(得分:-1)
是的,您需要转换为字符串才能找到长度。例如
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.