如何在JavaScript中输出带有前导零的数字

JavaScript

阿飞Pro

2020-03-12

我可以用math.round舍入到小数位数的x位数,但是有没有办法舍入到小数点的左边?例如,如果我指定2个位置,则5变为05

第1243篇《如何在JavaScript中输出带有前导零的数字》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

3个回答
阳光Mandy 2020.03.12

https://gist.github.com/1180489

function pad(a,b){return(1e15+a+"").slice(-b)}

有评论:

function pad(
  a, // the number to convert 
  b // number of resulting characters
){
  return (
    1e15 + a + // combine with large number
    "" // convert to string
  ).slice(-b) // cut leading "1"
}
Tony伽罗米亚 2020.03.12

您可以扩展Number对象:

Number.prototype.pad = function(size) {
    var s = String(this);
    while (s.length < (size || 2)) {s = "0" + s;}
    return s;
}

例子:

(9).pad();  //returns "09"

(7).pad(3);  //returns "007"
梅小宇宙 2020.03.12
function zfill(num, len) {return (Array(len).join("0") + num).slice(-len);}

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android