我要在JavaScript或jQuery中获得一个数字的长度?
我尝试过价值。长度没有任何成功,我需要先将其转换为字符串吗?
我要在JavaScript或jQuery中获得一个数字的长度?
我尝试过价值。长度没有任何成功,我需要先将其转换为字符串吗?
当前回答
我想纠正@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 x = 1234567;
x.toString().length;
这个过程也适用于浮点数和指数数。
为了求长度,你必须把数字变成字符串
var num = 123;
alert((num + "").length);
or
alert(num.toString().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;
}
var x = 1234567;
String(x).length;
它比. tostring()(在接受的答案中)短。
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});