如何用前导零来填充一个值?

时间:2022-05-26 21:27:30

What is the recommended way to zerofill a value in JavaScript? I imagine I could build a custom function to pad zeros on to a typecasted value, but I'm wondering if there is a more direct way to do this?

在JavaScript中,推荐的方法是什么?我想我可以构建一个自定义函数,将0填充到一个已排版的值上,但是我想知道是否有更直接的方法来实现这一点?

Note: By "zerofilled" I mean it in the database sense of the word (where a 6-digit zerofilled representation of the number 5 would be "000005").

注意:我说的“零填充”是指这个词的数据库含义(其中数字5的6位零填充表示为“000005”)。

67 个解决方案

#1


156  

Note to readers!

致读者!

As commenters have pointed out, this solution is "clever", and as clever solutions often are, it's memory intensive and relatively slow. If performance is a concern for you, don't use this solution!

正如评论者指出的那样,这个解决方案是“聪明的”,而且由于聪明的解决方案通常是,它的内存密集型和相对缓慢的。如果性能是您关心的问题,不要使用此解决方案!

Potentially outdated: ECMAScript 2017 includes String.prototype.padStart and Number.prototype.toLocaleString is there since ECMAScript 3.1. Example:

可能过时:ECMAScript 2017包含String.prototype。padStart Number.prototype。从ECMAScript 3.1开始,toLocaleString就在那里。例子:

var n=-0.1;
n.toLocaleString('en', {minimumIntegerDigits:4,minimumFractionDigits:2,useGrouping:false})

...will output "-0000.10".

…将输出“-0000.10”。

// or 
const padded = (.1+"").padStart(6,"0");
`-${padded}`

...will output "-0000.1".

…将输出“-0000.1”。

A simple function is all you need

一个简单的函数就足够了

function zeroFill( number, width )
{
  width -= number.toString().length;
  if ( width > 0 )
  {
    return new Array( width + (/\./.test( number ) ? 2 : 1) ).join( '0' ) + number;
  }
  return number + ""; // always return a string
}

you could bake this into a library if you want to conserve namespace or whatever. Like with jQuery's extend.

如果您希望保存名称空间或其他内容,可以将其放入库中。像jQuery的扩展。

#2


267  

Simple way. You could add string multiplication for the pad and turn it into a function.

简单的方法。您可以为该pad添加字符串乘法并将其转换为函数。

var pad = "000000";
var n = '5';
var result = (pad+n).slice(-pad.length);

As a function,

作为一个函数,

function paddy(num, padlen, padchar) {
    var pad_char = typeof padchar !== 'undefined' ? padchar : '0';
    var pad = new Array(1 + padlen).join(pad_char);
    return (pad + num).slice(-pad.length);
}
var fu = paddy(14, 5); // 00014
var bar = paddy(2, 4, '#'); // ###2

#3


206  

I can't believe all the complex answers on here...just use this:

我不敢相信这里所有复杂的答案……就用这个:


var zerofilled = ('0000'+n).slice(-4);

#4


99  

I actually had to come up with something like this recently. I figured there had to be a way to do it without using loops.

我最近不得不想出这样的办法。我认为必须有一种不用循环的方法。

This is what I came up with.

这就是我想到的。

function zeroPad(num, numZeros) {
    var n = Math.abs(num);
    var zeros = Math.max(0, numZeros - Math.floor(n).toString().length );
    var zeroString = Math.pow(10,zeros).toString().substr(1);
    if( num < 0 ) {
        zeroString = '-' + zeroString;
    }

    return zeroString+n;
}

Then just use it providing a number to zero pad:

然后使用它提供一个数字到0的pad:

> zeroPad(50,4);
"0050"

If the number is larger than the padding, the number will expand beyond the padding:

如果数字大于填充物,数字将会超出填充物的范围:

> zeroPad(51234, 3);
"51234"

Decimals are fine too!

小数也很好!

> zeroPad(51.1234, 4);
"0051.1234"

If you don't mind polluting the global namespace you can add it to Number directly:

如果您不介意污染全局命名空间,您可以直接将其添加到Number中:

Number.prototype.leftZeroPad = function(numZeros) {
    var n = Math.abs(this);
    var zeros = Math.max(0, numZeros - Math.floor(n).toString().length );
    var zeroString = Math.pow(10,zeros).toString().substr(1);
    if( this < 0 ) {
        zeroString = '-' + zeroString;
    }

    return zeroString+n;
}

And if you'd rather have decimals take up space in the padding:

如果你想让小数占据空格的话:

Number.prototype.leftZeroPad = function(numZeros) {
    var n = Math.abs(this);
    var zeros = Math.max(0, numZeros - n.toString().length );
    var zeroString = Math.pow(10,zeros).toString().substr(1);
    if( this < 0 ) {
        zeroString = '-' + zeroString;
    }

    return zeroString+n;
}

Cheers!

干杯!



XDR came up with a logarithmic variation that seems to perform better.

XDR提出了一种对数变异,似乎表现得更好。

WARNING: This function fails if num equals zero (e.g. zeropad(0, 2))

警告:如果num = 0(如zeropad(0,2)),该函数将失败。

function zeroPad (num, numZeros) {
    var an = Math.abs (num);
    var digitCount = 1 + Math.floor (Math.log (an) / Math.LN10);
    if (digitCount >= numZeros) {
        return num;
    }
    var zeroString = Math.pow (10, numZeros - digitCount).toString ().substr (1);
    return num < 0 ? '-' + zeroString + an : zeroString + an;
}

Speaking of performance, tomsmeding compared the top 3 answers (4 with the log variation). Guess which one majorly outperformed the other two? :)

说到性能,tomsmeding比较了前3个答案(4和日志变化)。你猜哪一个比另外两个好?:)

#5


50  

Here's what I used to pad a number up to 7 characters.

这里是我用来填充最多7个字符的代码。

("0000000" + number).slice(-7)

This approach will probably suffice for most people.

这种方法可能对大多数人都足够了。

Edit: If you want to make it more generic you can do this:

编辑:如果你想让它更通用,你可以这样做:

("0".repeat(padding) + number).slice(-padding)

#6


20  

If the fill number is known in advance not to exceed a certain value, there's another way to do this with no loops:

如果事先知道填充数不超过某个值,还有另一种方法可以在没有循环的情况下完成:

var fillZeroes = "00000000000000000000";  // max number of zero fill ever asked for in global

function zeroFill(number, width) {
    // make sure it's a string
    var input = number + "";  
    var prefix = "";
    if (input.charAt(0) === '-') {
        prefix = "-";
        input = input.slice(1);
        --width;
    }
    var fillAmt = Math.max(width - input.length, 0);
    return prefix + fillZeroes.slice(0, fillAmt) + input;
}

Test cases here: http://jsfiddle.net/jfriend00/N87mZ/

测试用例:http://jsfiddle.net/jfriend00/N87mZ/

#7


20  

Unfortunately, there are a lot of needless complicated suggestions for this problem, typically involving writing your own function to do math or string manipulation or calling a third-party utility. However, there is a standard way of doing this in the base JavaScript library with just one line of code. It might be worth wrapping this one line of code in a function to avoid having to specify parameters that you never want to change like the local name or style.

不幸的是,对于这个问题,有很多不必要的复杂建议,通常包括编写自己的函数来进行数学运算或字符串处理,或者调用第三方实用程序。但是,在基本的JavaScript库中,只有一行代码就可以实现这一点。在函数中包装这一行代码可能是值得的,以避免必须指定您永远不希望更改的参数,比如本地名称或样式。

var amount = 5;

var text = amount.toLocaleString('en-US',
{
    style: 'decimal',
    minimumIntegerDigits: 3,
    useGrouping: false
});

This will produce the value of "005" for text. You can also use the toLocaleString function of Number to pad zeros to the right side of the decimal point.

这将为文本生成“005”的值。您还可以使用数字的toLocaleString函数将0写到小数点右边。

var amount = 5;

var text = amount.toLocaleString('en-US',
{
    style: 'decimal',
    minimumFractionDigits: 2,
    useGrouping: false
});

This will produce the value of "5.00" for text. Change useGrouping to true to use comma separators for thousands.

这将产生文本的“5.00”值。将使用分组更改为true以使用逗号分隔符。

Note that using toLocaleString() with locales and options arguments is standardized separately in ECMA-402, not in ECMAScript. As of today, some browsers only implement basic support, i.e. toLocaleString() may ignore any arguments.

注意,使用带有地区和选项参数的toLocaleString()在ECMA-402中是单独标准化的,而不是在ECMAScript中。到目前为止,一些浏览器只实现基本的支持,比如toLocaleString()可能会忽略任何参数。

Complete Example

完整的示例

#8


17  

The quick and dirty way:

快速而肮脏的方式:

y = (new Array(count + 1 - x.toString().length)).join('0') + x;

For x = 5 and count = 6 you'll have y = "000005"

x = 5, count = 6 y = "000005"

#9


15  

In a proposed (stage 3) ES2017 method .padStart() you can simply now do (when implemented/supported):

在建议的(第3阶段)ES2017方法中。

string.padStart(maxLength, "0"); //max length is the max string length, not max # of fills

#10


12  

Here's a quick function I came up with to do the job. If anyone has a simpler approach, feel free to share!

这是我想出的一个快速函数。如果有人有更简单的方法,请随意分享!

function zerofill(number, length) {
    // Setup
    var result = number.toString();
    var pad = length - result.length;

    while(pad > 0) {
        result = '0' + result;
        pad--;
    }

    return result;
}

#11


11  

Late to the party here, but I often use this construct for doing ad-hoc padding of some value n, known to be a positive, decimal:

这里的聚会比较晚,但是我经常使用这个构造来做一些值n的特殊填充,已知是一个正数,小数:

(offset + n + '').substr(1);

Where offset is 10^^digits.

抵消在哪里10 ^ ^位数。

E.g. Padding to 5 digits, where n = 123:

例如,填充到5位,其中n = 123:

(1e5 + 123 + '').substr(1); // => 00123

The hexidecimal version of this is slightly more verbose:

hexidecimal版本则略显冗长:

(0x100000 + 0x123).toString(16).substr(1); // => 00123

Note 1: I like @profitehlolz's solution as well, which is the string version of this, using slice()'s nifty negative-index feature.

注意1:我也喜欢@profitehlolz的解决方案,它是这个解决方案的字符串版本,使用slice()漂亮的负索引特性。

#12


11  

I really don't know why, but no one did it in the most obvious way. Here it's my implementation.

我真的不知道为什么,但没有人以最明显的方式做这件事。这里是我实现。

Function:

功能:

/** Pad a number with 0 on the left */
function zeroPad(number, digits) {
    var num = number+"";
    while(num.length < digits){
        num='0'+num;
    }
    return num;
}

Prototype:

原型:

Number.prototype.zeroPad=function(digits){
    var num=this+"";
    while(num.length < digits){
        num='0'+num;
    }
    return(num);
};

Very straightforward, I can't see any way how this can be any simpler. For some reason I've seem many times here on SO, people just try to avoid 'for' and 'while' loops at any cost. Using regex will probably cost way more cycles for such a trivial 8 digit padding.

非常简单,我不知道怎么能更简单。出于某种原因,我在这里已经出现过很多次了,所以人们总是尽量避免“For”和“while”循环。使用regex可能需要花费更多的周期来处理如此微不足道的8位数填充。

#13


9  

I use this snipet to get a 5 digits representation

我用这个snipet得到一个5位数的表示

(value+100000).toString().slice(-5) // "00123" with value=123

#14


8  

The power of Math!

数学的力量!

x = integer to pad
y = number of zeroes to pad

x =整数到pad y = 0到pad的个数

function zeroPad(x, y)
{
   y = Math.max(y-1,0);
   var n = (x / Math.pow(10,y)).toFixed(y);
   return n.replace('.','');  
}

#15


7  

Don't reinvent the wheel, use underscore string:

不要重新发明*,使用下划线:

jsFiddle

jsFiddle

var numToPad = '5';

alert(_.str.pad(numToPad, 6, '0')); // yields: '000005'

#16


7  

This is the ES6 solution.

这是ES6解。

function pad(num, len) {
  return '0'.repeat(len - num.toString().length) + num;
}
alert(pad(1234,6));

#17


6  

After a, long, long time of testing 15 different functions/methods found in this questions answers, I now know which is the best (the most versatile and quickest).

经过长时间的测试,我发现在这个问题的答案中有15种不同的功能/方法,我现在知道哪个是最好的(最通用和最快的)。

I took 15 functions/methods from the answers to this question and made a script to measure the time taken to execute 100 pads. Each pad would pad the number 9 with 2000 zeros. This may seem excessive, and it is, but it gives you a good idea about the scaling of the functions.

我从这个问题的答案中选取了15个函数/方法,并编写了一个脚本来度量执行100个pad所需的时间。每一个便笺簿都会在数字9上加上2000个0。这看起来有点过分,但它给了你一个关于函数缩放的好主意。

The code I used can be found here: https://gist.github.com/NextToNothing/6325915

我使用的代码可以在这里找到:https://gist.github.com/NextToNothing/6325915

Feel free to modify and test the code yourself.

请随意修改和测试代码。

In order to get the most versatile method, you have to use a loop. This is because with very large numbers others are likely to fail, whereas, this will succeed.

为了获得最通用的方法,您必须使用循环。这是因为有很多人可能会失败,而这将会成功。

So, which loop to use? Well, that would be a while loop. A for loop is still fast, but a while loop is just slightly quicker(a couple of ms) - and cleaner.

那么,使用哪个循环呢?这是一个while循环。for循环仍然是快速的,但是while循环稍微快一些(一些ms) -和更干净。

Answers like those by Wilco, Aleksandar Toplek or Vitim.us will do the job perfectly.

像Wilco、Aleksandar Toplek或Vitim的回答。我们会把工作做好的。

Personally, I tried a different approach. I tried to use a recursive function to pad the string/number. It worked out better than methods joining an array but, still, didn't work as quick as a for loop.

就我个人而言,我尝试了另一种方法。我尝试使用递归函数来填充字符串/数字。它比加入数组的方法效果更好,但是仍然没有for循环那么快。

My function is:

我的功能是:

function pad(str, max, padder) {
  padder = typeof padder === "undefined" ? "0" : padder;
  return str.toString().length < max ? pad(padder.toString() + str, max, padder) : str;
}

You can use my function with, or without, setting the padding variable. So like this:

您可以使用我的函数来设置填充变量,也可以不设置。所以是这样的:

pad(1, 3); // Returns '001'
// - Or -
pad(1, 3, "x"); // Returns 'xx1'

Personally, after my tests, I would use a method with a while loop, like Aleksandar Toplek or Vitim.us. However, I would modify it slightly so that you are able to set the padding string.

就我个人而言,在测试之后,我将使用带有while循环的方法,如Aleksandar Toplek或Vitim.us。但是,我将稍微修改它,以便您能够设置填充字符串。

So, I would use this code:

因此,我将使用这个代码:

function padLeft(str, len, pad) {
    pad = typeof pad === "undefined" ? "0" : pad + "";
    str = str + "";
    while(str.length < len) {
        str = pad + str;
    }
    return str;
}

// Usage
padLeft(1, 3); // Returns '001'
// - Or -
padLeft(1, 3, "x"); // Returns 'xx1'

You could also use it as a prototype function, by using this code:

您也可以将其作为原型函数,使用以下代码:

Number.prototype.padLeft = function(len, pad) {
    pad = typeof pad === "undefined" ? "0" : pad + "";
    var str = this + "";
    while(str.length < len) {
        str = pad + str;
    }
    return str;
}

// Usage
var num = 1;

num.padLeft(3); // Returns '001'
// - Or -
num.padLeft(3, "x"); // Returns 'xx1'

#18


6  

First parameter is any real number, second parameter is a positive integer specifying the minimum number of digits to the left of the decimal point and third parameter is an optional positive integer specifying the number if digits to the right of the decimal point.

第一个参数是任何实数,第二个参数是一个正整数,指定小数点左边的最小位数;第三个参数是一个可选的正整数,指定小数点右边的位数。

function zPad(n, l, r){
    return(a=String(n).match(/(^-?)(\d*)\.?(\d*)/))?a[1]+(Array(l).join(0)+a[2]).slice(-Math.max(l,a[2].length))+('undefined'!==typeof r?(0<r?'.':'')+(a[3]+Array(r+1).join(0)).slice(0,r):a[3]?'.'+a[3]:''):0
}

so

所以

           zPad(6, 2) === '06'
          zPad(-6, 2) === '-06'
       zPad(600.2, 2) === '600.2'
        zPad(-600, 2) === '-600'
         zPad(6.2, 3) === '006.2'
        zPad(-6.2, 3) === '-006.2'
      zPad(6.2, 3, 0) === '006'
        zPad(6, 2, 3) === '06.000'
    zPad(600.2, 2, 3) === '600.200'
zPad(-600.1499, 2, 3) === '-600.149'

#19


6  

I didn't see anyone point out the fact that when you use String.prototype.substr() with a negative number it counts from the right.

我没看到有人指出这样一个事实:当你使用String.prototype.substr()时,它从右边开始计数。

A one liner solution to the OP's question, a 6-digit zerofilled representation of the number 5, is:

OP问题的一个线性解决方案(数字5的6位零填充表示)是:

console.log(("00000000" + 5).substr(-6));

Generalizing we'll get:

概括我们会得到:

function pad(num, len) { return ("00000000" + num).substr(-len) };

console.log(pad(5, 6));
console.log(pad(45, 6));
console.log(pad(345, 6));
console.log(pad(2345, 6));
console.log(pad(12345, 6));

#20


5  

ECMAScript 2017: use padStart or padEnd

ECMAScript 2017:使用padStart或padEnd

'abc'.padStart(10);         // "       abc"
'abc'.padStart(10, "foo");  // "foofoofabc"
'abc'.padStart(6,"123465"); // "123abc"

More info:

更多信息:

#21


4  

The latest way to do this is much simpler:

要做到这一点,最新的方法要简单得多:

var number = 2
number.toLocaleString(undefined, {minimumIntegerDigits:2})

output: "02"

输出:“02”

#22


3  

This one is less native, but may be the fastest...

这一种不太本土化,但可能是最快的……

zeroPad = function (num, count) {
    var pad = (num + '').length - count;
    while(--pad > -1) {
        num = '0' + num;
    }
    return num;
};

#23


3  

My solution

我的解决方案

Number.prototype.PadLeft = function (length, digit) {
    var str = '' + this;
    while (str.length < length) {
        str = (digit || '0') + str;
    }
    return str;
};

Usage

使用

var a = 567.25;
a.PadLeft(10); // 0000567.25

var b = 567.25;
b.PadLeft(20, '2'); // 22222222222222567.25

#24


3  

Not that this question needs more answers, but I thought I would add the simple lodash version of this.

并不是说这个问题需要更多的答案,但是我想我应该加上这个的简单的lodash版本。

_.padLeft(number, 6, '0')

_。padLeft(6 ' 0 ')

#25


3  

Just an another solution, but I think it's more legible.

只是另一种解决方案,但我认为它更容易理解。

function zeroFill(text, size)
{
  while (text.length < size){
  	text = "0" + text;
  }
  
  return text;
}

#26


3  

Why not use recursion?

为什么不使用递归?

function padZero(s, n) {
    s = s.toString(); // in case someone passes a number
    return s.length >= n ? s : padZero('0' + s, n);
}

#27


2  

Some monkeypatching also works

一些monkeypatching同样适用

String.prototype.padLeft = function (n, c) {
  if (isNaN(n))
    return null;
  c = c || "0";
  return (new Array(n).join(c).substring(0, this.length-n)) + this; 
};
var paddedValue = "123".padLeft(6); // returns "000123"
var otherPadded = "TEXT".padLeft(8, " "); // returns "    TEXT"

#28


2  

function pad(toPad, padChar, length){
    return (String(toPad).length < length)
        ? new Array(length - String(toPad).length + 1).join(padChar) + String(toPad)
        : toPad;
}

pad(5, 0, 6) = 000005

pad(5,0,6) = 000005

pad('10', 0, 2) = 10 // don't pad if not necessary

pad('10', 0,2) = 10 //不需要时不要使用pad

pad('S', 'O', 2) = SO

pad('S', 'O', 2) = SO

...etc.

…等。

Cheers

干杯

#29


2  

The simplest, most straight-forward solution you will find.

你会发现最简单,最直接的解决方法。

function zerofill(number,length) {
    var output = number.toString();
    while(output.length < length) {
      output = '0' + output;
    }
    return output;
}

#30


2  

Just for fun, here's my version of a pad function:

只是为了好玩,这是我的pad功能:

function pad(num, len) {
  return Array(len + 1 - num.toString().length).join('0') + num;
}

It also won't truncate numbers longer than the padding length

它也不会比填充长度更长的截断数字

#1


156  

Note to readers!

致读者!

As commenters have pointed out, this solution is "clever", and as clever solutions often are, it's memory intensive and relatively slow. If performance is a concern for you, don't use this solution!

正如评论者指出的那样,这个解决方案是“聪明的”,而且由于聪明的解决方案通常是,它的内存密集型和相对缓慢的。如果性能是您关心的问题,不要使用此解决方案!

Potentially outdated: ECMAScript 2017 includes String.prototype.padStart and Number.prototype.toLocaleString is there since ECMAScript 3.1. Example:

可能过时:ECMAScript 2017包含String.prototype。padStart Number.prototype。从ECMAScript 3.1开始,toLocaleString就在那里。例子:

var n=-0.1;
n.toLocaleString('en', {minimumIntegerDigits:4,minimumFractionDigits:2,useGrouping:false})

...will output "-0000.10".

…将输出“-0000.10”。

// or 
const padded = (.1+"").padStart(6,"0");
`-${padded}`

...will output "-0000.1".

…将输出“-0000.1”。

A simple function is all you need

一个简单的函数就足够了

function zeroFill( number, width )
{
  width -= number.toString().length;
  if ( width > 0 )
  {
    return new Array( width + (/\./.test( number ) ? 2 : 1) ).join( '0' ) + number;
  }
  return number + ""; // always return a string
}

you could bake this into a library if you want to conserve namespace or whatever. Like with jQuery's extend.

如果您希望保存名称空间或其他内容,可以将其放入库中。像jQuery的扩展。

#2


267  

Simple way. You could add string multiplication for the pad and turn it into a function.

简单的方法。您可以为该pad添加字符串乘法并将其转换为函数。

var pad = "000000";
var n = '5';
var result = (pad+n).slice(-pad.length);

As a function,

作为一个函数,

function paddy(num, padlen, padchar) {
    var pad_char = typeof padchar !== 'undefined' ? padchar : '0';
    var pad = new Array(1 + padlen).join(pad_char);
    return (pad + num).slice(-pad.length);
}
var fu = paddy(14, 5); // 00014
var bar = paddy(2, 4, '#'); // ###2

#3


206  

I can't believe all the complex answers on here...just use this:

我不敢相信这里所有复杂的答案……就用这个:


var zerofilled = ('0000'+n).slice(-4);

#4


99  

I actually had to come up with something like this recently. I figured there had to be a way to do it without using loops.

我最近不得不想出这样的办法。我认为必须有一种不用循环的方法。

This is what I came up with.

这就是我想到的。

function zeroPad(num, numZeros) {
    var n = Math.abs(num);
    var zeros = Math.max(0, numZeros - Math.floor(n).toString().length );
    var zeroString = Math.pow(10,zeros).toString().substr(1);
    if( num < 0 ) {
        zeroString = '-' + zeroString;
    }

    return zeroString+n;
}

Then just use it providing a number to zero pad:

然后使用它提供一个数字到0的pad:

> zeroPad(50,4);
"0050"

If the number is larger than the padding, the number will expand beyond the padding:

如果数字大于填充物,数字将会超出填充物的范围:

> zeroPad(51234, 3);
"51234"

Decimals are fine too!

小数也很好!

> zeroPad(51.1234, 4);
"0051.1234"

If you don't mind polluting the global namespace you can add it to Number directly:

如果您不介意污染全局命名空间,您可以直接将其添加到Number中:

Number.prototype.leftZeroPad = function(numZeros) {
    var n = Math.abs(this);
    var zeros = Math.max(0, numZeros - Math.floor(n).toString().length );
    var zeroString = Math.pow(10,zeros).toString().substr(1);
    if( this < 0 ) {
        zeroString = '-' + zeroString;
    }

    return zeroString+n;
}

And if you'd rather have decimals take up space in the padding:

如果你想让小数占据空格的话:

Number.prototype.leftZeroPad = function(numZeros) {
    var n = Math.abs(this);
    var zeros = Math.max(0, numZeros - n.toString().length );
    var zeroString = Math.pow(10,zeros).toString().substr(1);
    if( this < 0 ) {
        zeroString = '-' + zeroString;
    }

    return zeroString+n;
}

Cheers!

干杯!



XDR came up with a logarithmic variation that seems to perform better.

XDR提出了一种对数变异,似乎表现得更好。

WARNING: This function fails if num equals zero (e.g. zeropad(0, 2))

警告:如果num = 0(如zeropad(0,2)),该函数将失败。

function zeroPad (num, numZeros) {
    var an = Math.abs (num);
    var digitCount = 1 + Math.floor (Math.log (an) / Math.LN10);
    if (digitCount >= numZeros) {
        return num;
    }
    var zeroString = Math.pow (10, numZeros - digitCount).toString ().substr (1);
    return num < 0 ? '-' + zeroString + an : zeroString + an;
}

Speaking of performance, tomsmeding compared the top 3 answers (4 with the log variation). Guess which one majorly outperformed the other two? :)

说到性能,tomsmeding比较了前3个答案(4和日志变化)。你猜哪一个比另外两个好?:)

#5


50  

Here's what I used to pad a number up to 7 characters.

这里是我用来填充最多7个字符的代码。

("0000000" + number).slice(-7)

This approach will probably suffice for most people.

这种方法可能对大多数人都足够了。

Edit: If you want to make it more generic you can do this:

编辑:如果你想让它更通用,你可以这样做:

("0".repeat(padding) + number).slice(-padding)

#6


20  

If the fill number is known in advance not to exceed a certain value, there's another way to do this with no loops:

如果事先知道填充数不超过某个值,还有另一种方法可以在没有循环的情况下完成:

var fillZeroes = "00000000000000000000";  // max number of zero fill ever asked for in global

function zeroFill(number, width) {
    // make sure it's a string
    var input = number + "";  
    var prefix = "";
    if (input.charAt(0) === '-') {
        prefix = "-";
        input = input.slice(1);
        --width;
    }
    var fillAmt = Math.max(width - input.length, 0);
    return prefix + fillZeroes.slice(0, fillAmt) + input;
}

Test cases here: http://jsfiddle.net/jfriend00/N87mZ/

测试用例:http://jsfiddle.net/jfriend00/N87mZ/

#7


20  

Unfortunately, there are a lot of needless complicated suggestions for this problem, typically involving writing your own function to do math or string manipulation or calling a third-party utility. However, there is a standard way of doing this in the base JavaScript library with just one line of code. It might be worth wrapping this one line of code in a function to avoid having to specify parameters that you never want to change like the local name or style.

不幸的是,对于这个问题,有很多不必要的复杂建议,通常包括编写自己的函数来进行数学运算或字符串处理,或者调用第三方实用程序。但是,在基本的JavaScript库中,只有一行代码就可以实现这一点。在函数中包装这一行代码可能是值得的,以避免必须指定您永远不希望更改的参数,比如本地名称或样式。

var amount = 5;

var text = amount.toLocaleString('en-US',
{
    style: 'decimal',
    minimumIntegerDigits: 3,
    useGrouping: false
});

This will produce the value of "005" for text. You can also use the toLocaleString function of Number to pad zeros to the right side of the decimal point.

这将为文本生成“005”的值。您还可以使用数字的toLocaleString函数将0写到小数点右边。

var amount = 5;

var text = amount.toLocaleString('en-US',
{
    style: 'decimal',
    minimumFractionDigits: 2,
    useGrouping: false
});

This will produce the value of "5.00" for text. Change useGrouping to true to use comma separators for thousands.

这将产生文本的“5.00”值。将使用分组更改为true以使用逗号分隔符。

Note that using toLocaleString() with locales and options arguments is standardized separately in ECMA-402, not in ECMAScript. As of today, some browsers only implement basic support, i.e. toLocaleString() may ignore any arguments.

注意,使用带有地区和选项参数的toLocaleString()在ECMA-402中是单独标准化的,而不是在ECMAScript中。到目前为止,一些浏览器只实现基本的支持,比如toLocaleString()可能会忽略任何参数。

Complete Example

完整的示例

#8


17  

The quick and dirty way:

快速而肮脏的方式:

y = (new Array(count + 1 - x.toString().length)).join('0') + x;

For x = 5 and count = 6 you'll have y = "000005"

x = 5, count = 6 y = "000005"

#9


15  

In a proposed (stage 3) ES2017 method .padStart() you can simply now do (when implemented/supported):

在建议的(第3阶段)ES2017方法中。

string.padStart(maxLength, "0"); //max length is the max string length, not max # of fills

#10


12  

Here's a quick function I came up with to do the job. If anyone has a simpler approach, feel free to share!

这是我想出的一个快速函数。如果有人有更简单的方法,请随意分享!

function zerofill(number, length) {
    // Setup
    var result = number.toString();
    var pad = length - result.length;

    while(pad > 0) {
        result = '0' + result;
        pad--;
    }

    return result;
}

#11


11  

Late to the party here, but I often use this construct for doing ad-hoc padding of some value n, known to be a positive, decimal:

这里的聚会比较晚,但是我经常使用这个构造来做一些值n的特殊填充,已知是一个正数,小数:

(offset + n + '').substr(1);

Where offset is 10^^digits.

抵消在哪里10 ^ ^位数。

E.g. Padding to 5 digits, where n = 123:

例如,填充到5位,其中n = 123:

(1e5 + 123 + '').substr(1); // => 00123

The hexidecimal version of this is slightly more verbose:

hexidecimal版本则略显冗长:

(0x100000 + 0x123).toString(16).substr(1); // => 00123

Note 1: I like @profitehlolz's solution as well, which is the string version of this, using slice()'s nifty negative-index feature.

注意1:我也喜欢@profitehlolz的解决方案,它是这个解决方案的字符串版本,使用slice()漂亮的负索引特性。

#12


11  

I really don't know why, but no one did it in the most obvious way. Here it's my implementation.

我真的不知道为什么,但没有人以最明显的方式做这件事。这里是我实现。

Function:

功能:

/** Pad a number with 0 on the left */
function zeroPad(number, digits) {
    var num = number+"";
    while(num.length < digits){
        num='0'+num;
    }
    return num;
}

Prototype:

原型:

Number.prototype.zeroPad=function(digits){
    var num=this+"";
    while(num.length < digits){
        num='0'+num;
    }
    return(num);
};

Very straightforward, I can't see any way how this can be any simpler. For some reason I've seem many times here on SO, people just try to avoid 'for' and 'while' loops at any cost. Using regex will probably cost way more cycles for such a trivial 8 digit padding.

非常简单,我不知道怎么能更简单。出于某种原因,我在这里已经出现过很多次了,所以人们总是尽量避免“For”和“while”循环。使用regex可能需要花费更多的周期来处理如此微不足道的8位数填充。

#13


9  

I use this snipet to get a 5 digits representation

我用这个snipet得到一个5位数的表示

(value+100000).toString().slice(-5) // "00123" with value=123

#14


8  

The power of Math!

数学的力量!

x = integer to pad
y = number of zeroes to pad

x =整数到pad y = 0到pad的个数

function zeroPad(x, y)
{
   y = Math.max(y-1,0);
   var n = (x / Math.pow(10,y)).toFixed(y);
   return n.replace('.','');  
}

#15


7  

Don't reinvent the wheel, use underscore string:

不要重新发明*,使用下划线:

jsFiddle

jsFiddle

var numToPad = '5';

alert(_.str.pad(numToPad, 6, '0')); // yields: '000005'

#16


7  

This is the ES6 solution.

这是ES6解。

function pad(num, len) {
  return '0'.repeat(len - num.toString().length) + num;
}
alert(pad(1234,6));

#17


6  

After a, long, long time of testing 15 different functions/methods found in this questions answers, I now know which is the best (the most versatile and quickest).

经过长时间的测试,我发现在这个问题的答案中有15种不同的功能/方法,我现在知道哪个是最好的(最通用和最快的)。

I took 15 functions/methods from the answers to this question and made a script to measure the time taken to execute 100 pads. Each pad would pad the number 9 with 2000 zeros. This may seem excessive, and it is, but it gives you a good idea about the scaling of the functions.

我从这个问题的答案中选取了15个函数/方法,并编写了一个脚本来度量执行100个pad所需的时间。每一个便笺簿都会在数字9上加上2000个0。这看起来有点过分,但它给了你一个关于函数缩放的好主意。

The code I used can be found here: https://gist.github.com/NextToNothing/6325915

我使用的代码可以在这里找到:https://gist.github.com/NextToNothing/6325915

Feel free to modify and test the code yourself.

请随意修改和测试代码。

In order to get the most versatile method, you have to use a loop. This is because with very large numbers others are likely to fail, whereas, this will succeed.

为了获得最通用的方法,您必须使用循环。这是因为有很多人可能会失败,而这将会成功。

So, which loop to use? Well, that would be a while loop. A for loop is still fast, but a while loop is just slightly quicker(a couple of ms) - and cleaner.

那么,使用哪个循环呢?这是一个while循环。for循环仍然是快速的,但是while循环稍微快一些(一些ms) -和更干净。

Answers like those by Wilco, Aleksandar Toplek or Vitim.us will do the job perfectly.

像Wilco、Aleksandar Toplek或Vitim的回答。我们会把工作做好的。

Personally, I tried a different approach. I tried to use a recursive function to pad the string/number. It worked out better than methods joining an array but, still, didn't work as quick as a for loop.

就我个人而言,我尝试了另一种方法。我尝试使用递归函数来填充字符串/数字。它比加入数组的方法效果更好,但是仍然没有for循环那么快。

My function is:

我的功能是:

function pad(str, max, padder) {
  padder = typeof padder === "undefined" ? "0" : padder;
  return str.toString().length < max ? pad(padder.toString() + str, max, padder) : str;
}

You can use my function with, or without, setting the padding variable. So like this:

您可以使用我的函数来设置填充变量,也可以不设置。所以是这样的:

pad(1, 3); // Returns '001'
// - Or -
pad(1, 3, "x"); // Returns 'xx1'

Personally, after my tests, I would use a method with a while loop, like Aleksandar Toplek or Vitim.us. However, I would modify it slightly so that you are able to set the padding string.

就我个人而言,在测试之后,我将使用带有while循环的方法,如Aleksandar Toplek或Vitim.us。但是,我将稍微修改它,以便您能够设置填充字符串。

So, I would use this code:

因此,我将使用这个代码:

function padLeft(str, len, pad) {
    pad = typeof pad === "undefined" ? "0" : pad + "";
    str = str + "";
    while(str.length < len) {
        str = pad + str;
    }
    return str;
}

// Usage
padLeft(1, 3); // Returns '001'
// - Or -
padLeft(1, 3, "x"); // Returns 'xx1'

You could also use it as a prototype function, by using this code:

您也可以将其作为原型函数,使用以下代码:

Number.prototype.padLeft = function(len, pad) {
    pad = typeof pad === "undefined" ? "0" : pad + "";
    var str = this + "";
    while(str.length < len) {
        str = pad + str;
    }
    return str;
}

// Usage
var num = 1;

num.padLeft(3); // Returns '001'
// - Or -
num.padLeft(3, "x"); // Returns 'xx1'

#18


6  

First parameter is any real number, second parameter is a positive integer specifying the minimum number of digits to the left of the decimal point and third parameter is an optional positive integer specifying the number if digits to the right of the decimal point.

第一个参数是任何实数,第二个参数是一个正整数,指定小数点左边的最小位数;第三个参数是一个可选的正整数,指定小数点右边的位数。

function zPad(n, l, r){
    return(a=String(n).match(/(^-?)(\d*)\.?(\d*)/))?a[1]+(Array(l).join(0)+a[2]).slice(-Math.max(l,a[2].length))+('undefined'!==typeof r?(0<r?'.':'')+(a[3]+Array(r+1).join(0)).slice(0,r):a[3]?'.'+a[3]:''):0
}

so

所以

           zPad(6, 2) === '06'
          zPad(-6, 2) === '-06'
       zPad(600.2, 2) === '600.2'
        zPad(-600, 2) === '-600'
         zPad(6.2, 3) === '006.2'
        zPad(-6.2, 3) === '-006.2'
      zPad(6.2, 3, 0) === '006'
        zPad(6, 2, 3) === '06.000'
    zPad(600.2, 2, 3) === '600.200'
zPad(-600.1499, 2, 3) === '-600.149'

#19


6  

I didn't see anyone point out the fact that when you use String.prototype.substr() with a negative number it counts from the right.

我没看到有人指出这样一个事实:当你使用String.prototype.substr()时,它从右边开始计数。

A one liner solution to the OP's question, a 6-digit zerofilled representation of the number 5, is:

OP问题的一个线性解决方案(数字5的6位零填充表示)是:

console.log(("00000000" + 5).substr(-6));

Generalizing we'll get:

概括我们会得到:

function pad(num, len) { return ("00000000" + num).substr(-len) };

console.log(pad(5, 6));
console.log(pad(45, 6));
console.log(pad(345, 6));
console.log(pad(2345, 6));
console.log(pad(12345, 6));

#20


5  

ECMAScript 2017: use padStart or padEnd

ECMAScript 2017:使用padStart或padEnd

'abc'.padStart(10);         // "       abc"
'abc'.padStart(10, "foo");  // "foofoofabc"
'abc'.padStart(6,"123465"); // "123abc"

More info:

更多信息:

#21


4  

The latest way to do this is much simpler:

要做到这一点,最新的方法要简单得多:

var number = 2
number.toLocaleString(undefined, {minimumIntegerDigits:2})

output: "02"

输出:“02”

#22


3  

This one is less native, but may be the fastest...

这一种不太本土化,但可能是最快的……

zeroPad = function (num, count) {
    var pad = (num + '').length - count;
    while(--pad > -1) {
        num = '0' + num;
    }
    return num;
};

#23


3  

My solution

我的解决方案

Number.prototype.PadLeft = function (length, digit) {
    var str = '' + this;
    while (str.length < length) {
        str = (digit || '0') + str;
    }
    return str;
};

Usage

使用

var a = 567.25;
a.PadLeft(10); // 0000567.25

var b = 567.25;
b.PadLeft(20, '2'); // 22222222222222567.25

#24


3  

Not that this question needs more answers, but I thought I would add the simple lodash version of this.

并不是说这个问题需要更多的答案,但是我想我应该加上这个的简单的lodash版本。

_.padLeft(number, 6, '0')

_。padLeft(6 ' 0 ')

#25


3  

Just an another solution, but I think it's more legible.

只是另一种解决方案,但我认为它更容易理解。

function zeroFill(text, size)
{
  while (text.length < size){
  	text = "0" + text;
  }
  
  return text;
}

#26


3  

Why not use recursion?

为什么不使用递归?

function padZero(s, n) {
    s = s.toString(); // in case someone passes a number
    return s.length >= n ? s : padZero('0' + s, n);
}

#27


2  

Some monkeypatching also works

一些monkeypatching同样适用

String.prototype.padLeft = function (n, c) {
  if (isNaN(n))
    return null;
  c = c || "0";
  return (new Array(n).join(c).substring(0, this.length-n)) + this; 
};
var paddedValue = "123".padLeft(6); // returns "000123"
var otherPadded = "TEXT".padLeft(8, " "); // returns "    TEXT"

#28


2  

function pad(toPad, padChar, length){
    return (String(toPad).length < length)
        ? new Array(length - String(toPad).length + 1).join(padChar) + String(toPad)
        : toPad;
}

pad(5, 0, 6) = 000005

pad(5,0,6) = 000005

pad('10', 0, 2) = 10 // don't pad if not necessary

pad('10', 0,2) = 10 //不需要时不要使用pad

pad('S', 'O', 2) = SO

pad('S', 'O', 2) = SO

...etc.

…等。

Cheers

干杯

#29


2  

The simplest, most straight-forward solution you will find.

你会发现最简单,最直接的解决方法。

function zerofill(number,length) {
    var output = number.toString();
    while(output.length < length) {
      output = '0' + output;
    }
    return output;
}

#30


2  

Just for fun, here's my version of a pad function:

只是为了好玩,这是我的pad功能:

function pad(num, len) {
  return Array(len + 1 - num.toString().length).join('0') + num;
}

It also won't truncate numbers longer than the padding length

它也不会比填充长度更长的截断数字