Javascript 我怎样才能找到一个数字的长度?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10952615/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I find the length of a number?
提问by Code Junkie
I'm looking to get the length of a number in JavaScript or jQuery?
我想在 JavaScript 或 jQuery 中获取数字的长度?
I've tried value.length
without any success, do I need to convert this to a string first?
我试过value.length
没有任何成功,我需要先将它转换为字符串吗?
回答by thecodeparadox
var x = 1234567;
x.toString().length;
This process will also work forFloat Number
and for Exponential number
also.
这个过程也将努力为Float Number
和Exponential number
也。
回答by MaxArt
Ok, so many answers, but this is a pure math one, just for the fun or for remembering that Math is Important:
好吧,这么多答案,但这是一个纯粹的数学答案,只是为了好玩或记住数学很重要:
var len = Math.ceil(Math.log(num + 1) / Math.LN10);
This actually gives the "length" of the number even if it's in exponential form. num
is supposed to be a non negative integer here: if it's negative, take its absolute value and adjust the sign afterwards.
这实际上给出了数字的“长度”,即使它是指数形式的。num
在这里应该是一个非负整数:如果它是负数,则取其绝对值并在之后调整符号。
Update for ES2015
ES2015 更新
Now that Math.log10
is a thing, you can simply write
现在这Math.log10
是一件事,你可以简单地写
const len = Math.ceil(Math.log10(num + 1));
回答by Israfil Havilah
I've been using this functionality in node.js, this is my fastest implementation so far:
我一直在 node.js 中使用这个功能,这是我迄今为止最快的实现:
var nLength = function(n) {
return (Math.log(Math.abs(n)+1) * 0.43429448190325176 | 0) + 1;?
}
It should handle positive and negative integers (also in exponential form) and should return the length of integer part in floats.
它应该处理正整数和负整数(也是指数形式),并且应该以浮点数形式返回整数部分的长度。
The following reference should provide some insight into the method: Weisstein, Eric W. "Number Length." From MathWorld--A Wolfram Web Resource.
以下参考资料应提供对该方法的一些了解: Weisstein, Eric W.“Number Length”。来自 MathWorld--Wolfram Web 资源。
I believe that some bitwise operation can replace the Math.abs, but jsperf shows that Math.abs works just fine in the majority of js engines.
我相信一些按位运算可以代替 Math.abs,但 jsperf 表明 Math.abs 在大多数 js 引擎中都可以正常工作。
Update: As noted in the comments, this solution has some issues:(
更新:如评论中所述,此解决方案存在一些问题:(
Update2 (workaround): I believe that at some point precision issues kick in and the Math.log(...)*0.434...
just behaves unexpectedly. However, if Internet Explorer or Mobile devices are not your cup of tea, you can replace this operation with the Math.log10
function. In Node.js I wrote a quick basic test with the function nLength = (n) => 1 + Math.log10(Math.abs(n) + 1) | 0;
and with Math.log10
it worked as expected. Please note that Math.log10
is not universally supported.
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
并非普遍支持。
回答by Adil
You have to make the number to string in order to take length
你必须把数字串起来才能取长度
var num = 123;
alert((num + "").length);
or
或者
alert(num.toString().length);
回答by funador
Could also use a template string:
也可以使用模板字符串:
const num = 123456
`${num}`.length // 6
回答by Naftali aka Neal
Well without converting the integer to a string you could make a funky loop:
好吧,如果不将整数转换为字符串,您就可以制作一个时髦的循环:
var number = 20000;
var length = 0;
for(i = number; i > 1; ++i){
++length;
i = Math.floor(i/10);
}
alert(length);?
回答by tskuzzy
First convert it to a string:
首先将其转换为字符串:
var mynumber = 123;
alert((""+mynumber).length);
Adding an empty string to it will implicitly cause mynumber
to turn into a string.
向它添加一个空字符串将隐式导致mynumber
变成一个字符串。
回答by Eric Chen
There are three way to do it.
有三种方法可以做到。
var num = 123;
alert(num.toString().length);
better performance one (best performance in ie11)
更好的性能一(在 ie11 中的最佳性能)
var num = 123;
alert((num + '').length);
Math (best performance in Chrome, firefox but slowest in ie11)
数学(在 Chrome、firefox 中性能最佳,但在 ie11 中最慢)
var num = 123
alert(Math.floor( Math.log(num) / Math.LN10 ) + 1)
there is a jspref here http://jsperf.com/fastest-way-to-get-the-first-in-a-number/2
这里有一个 jspref http://jsperf.com/fastest-way-to-get-the-first-in-a-number/2
回答by Oliver Dixon
You should go for the simplest one (stringLength), readability always beats speed. But if you care about speed here are some below.
你应该选择最简单的(stringLength),可读性总是胜过速度。但如果你关心速度,这里有一些。
Three different methods all with varying speed.
三种不同的方法都具有不同的速度。
// 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);
}
回答by Adrian Lynch
I got asked a similar question in a test.
我在测试中被问到类似的问题。
Find a number's length without converting to string
查找数字的长度而不转换为字符串
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 ]
Negative numbers were added to complicate it a little more, hence the Math.abs().
添加负数使其更加复杂,因此 Math.abs()。