3

【笔记】JS指定数字位数

 1 year ago
source link: https://feiju12138.github.io/2022/07/29/JS%E6%8C%87%E5%AE%9A%E6%95%B0%E5%AD%97%E4%BD%8D%E6%95%B0/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

JS指定数字位数为固定的长度,如果不足,前面用0补齐

function PrefixInteger(num, length) {
for(let len = (num + "").length; len < length; len = num.length) {
num = "0" + num;
}
return num;
}

通过转换小数

function PrefixInteger(num, length) {
let decimal = num / Math.pow(10, length);
decimal = decimal.toFixed(length) + "";
return decimal.substr(decimal.indexOf(".")+1);
}
function PrefixInteger(num, length) {
return (Array(length).join('0') + num).slice(-length);
}

PHP中文网——(-)浩


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK