我要在JavaScript或jQuery中获得一个数字的长度?
我尝试过价值。长度没有任何成功,我需要先将其转换为字符串吗?
我要在JavaScript或jQuery中获得一个数字的长度?
我尝试过价值。长度没有任何成功,我需要先将其转换为字符串吗?
当前回答
也可以使用模板字符串:
const num = 123456
`${num}`.length // 6
其他回答
一种用于整数或整数部分长度的方法,无需将其常规转换为字符串:
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});
首先将其转换为字符串:
var mynumber = 123;
alert((""+mynumber).length);
添加一个空字符串将隐式地导致mynumber变成一个字符串。
我想纠正@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 len = Math.ceil(Math.log(num + 1) / Math.LN10);
这实际上给出了数字的“长度”,即使它是指数形式的。这里的Num应该是非负整数:如果它是负的,取它的绝对值,然后调整符号。
ES2015更新
现在是数学。Log10是一个东西,你可以简单地写出来
const len = Math.ceil(Math.log10(num + 1));