我要在JavaScript或jQuery中获得一个数字的长度?
我尝试过价值。长度没有任何成功,我需要先将其转换为字符串吗?
我要在JavaScript或jQuery中获得一个数字的长度?
我尝试过价值。长度没有任何成功,我需要先将其转换为字符串吗?
当前回答
也可以使用模板字符串:
const num = 123456
`${num}`.length // 6
其他回答
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;
}
为了获得任何由小数部分和小数部分分开的数字的相关位数(如果前导小数部分为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 mynumber = 123;
alert((""+mynumber).length);
添加一个空字符串将隐式地导致mynumber变成一个字符串。