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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2998784/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:50:49  来源:igfitidea点击:

How to output numbers with leading zeros in JavaScript

javascripttext-formattingnumber-formatting

提问by chris

I can round to x amount of decimal places with math.round but is there a way to round left of the decimal? for example 5 becomes 05 if I specify 2 places

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

回答by InfinitiesLoop

NOTE: Potentially outdated. ECMAScript 2017 includes String.prototype.padStart

注意:可能已经过时。ECMAScript 2017 包含String.prototype.padStart

You're asking for zero padding? Not really rounding. You'll have to convert it to a string since numbers don't make sense with leading zeros. Something like this...

你要求零填充?不是真的四舍五入。您必须将其转换为字符串,因为数字对前导零没有意义。像这样的东西...

function pad(num, size) {
    var s = num+"";
    while (s.length < size) s = "0" + s;
    return s;
}

Or if you know you'd never be using more than X number of zeros this might be better. This assumes you'd never want more than 10 digits.

或者,如果您知道您永远不会使用超过 X 个零,这可能会更好。这假设您永远不会想要超过 10 位数字。

function pad(num, size) {
    var s = "000000000" + num;
    return s.substr(s.length-size);
}

If you care about negative numbers you'll have to strip the "-" and readd it.

如果您关心负数,则必须去掉“-”并阅读它。

回答by Mild Fuzz

You could extend the Numberobject:

您可以扩展Number对象:

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

Examples:

例子:

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

(7).pad(3);  //returns "007"

回答by CMS

UPDATE:Small one-liner function using the ES2017 String.prototype.padStartmethod:

更新:使用 ES2017String.prototype.padStart方法的小型单行函数:

const zeroPad = (num, places) => String(num).padStart(places, '0')

console.log(zeroPad(5, 2)); // "05"
console.log(zeroPad(5, 4)); // "0005"
console.log(zeroPad(5, 6)); // "000005"
console.log(zeroPad(1234, 2)); // "1234"

Another ES5 approach:

另一种 ES5 方法:

function zeroPad(num, places) {
  var zero = places - num.toString().length + 1;
  return Array(+(zero > 0 && zero)).join("0") + num;
}

zeroPad(5, 2); // "05"
zeroPad(5, 4); // "0005"
zeroPad(5, 6); // "000005"
zeroPad(1234, 2); // "1234" :)

回答by dave1010

From https://gist.github.com/1180489

来自https://gist.github.com/1180489

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

With comments:

附评论:

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"
}

回答by ithinc

function zfill(num, len) {return (Array(len).join("0") + num).slice(-len);}

回答by Christoph

Just for fun (I had some time to kill), a more sophisticated implementation which caches the zero-string:

只是为了好玩(我有一些时间来消磨时间),一个更复杂的实现,它缓存零字符串:

pad.zeros = new Array(5).join('0');
function pad(num, len) {
    var str = String(num),
        diff = len - str.length;
    if(diff <= 0) return str;
    if(diff > pad.zeros.length)
        pad.zeros = new Array(diff + 1).join('0');
    return pad.zeros.substr(0, diff) + str;
}

If the padding count is large and the function is called often enough, it actually outperforms the other methods...

如果填充计数很大并且该函数被足够频繁地调用,它实际上优于其他方法......