我要在JavaScript或jQuery中获得一个数字的长度?
我尝试过价值。长度没有任何成功,我需要先将其转换为字符串吗?
我要在JavaScript或jQuery中获得一个数字的长度?
我尝试过价值。长度没有任何成功,我需要先将其转换为字符串吗?
当前回答
你应该使用最简单的字符串(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 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
var x = 1234567;
String(x).length;
它比. tostring()(在接受的答案中)短。
好吧,有这么多答案,但这是一个纯粹的数学问题,只是为了好玩,或者为了记住数学很重要:
var len = Math.ceil(Math.log(num + 1) / Math.LN10);
这实际上给出了数字的“长度”,即使它是指数形式的。这里的Num应该是非负整数:如果它是负的,取它的绝对值,然后调整符号。
ES2015更新
现在是数学。Log10是一个东西,你可以简单地写出来
const len = Math.ceil(Math.log10(num + 1));
为了获得任何由小数部分和小数部分分开的数字的相关位数(如果前导小数部分为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;
x.toString().length;
这个过程也适用于浮点数和指数数。