如何用前导零填充值?

发布于 2024-07-30 18:40:39 字数 165 浏览 15 评论 0原文

在 JavaScript 中对值进行零填充的推荐方法是什么? 我想我可以构建一个自定义函数来将零填充到类型转换的值上,但我想知道是否有更直接的方法来做到这一点?

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

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?

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").

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

吐个泡泡 2024-08-06 18:40:40

我不敢相信这里所有复杂的答案......只需使用这个:

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

let n = 1
var zerofilled = ('0000'+n).slice(-4);
console.log(zerofilled)

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

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

let n = 1
var zerofilled = ('0000'+n).slice(-4);
console.log(zerofilled)

计㈡愣 2024-08-06 18:40:40

自 ECMAScript 2017 起,我们有了 padStart

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

在 ECMAScript 2017 之前,

使用 toLocaleString

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

Since ECMAScript 2017 we have padStart:

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

Before ECMAScript 2017

With toLocaleString:

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

我要还你自由 2024-08-06 18:40:40

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

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

作为一个函数,

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

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

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
踏雪无痕 2024-08-06 18:40:40

事实上,我最近不得不想出这样的事情。
我认为必须有一种不使用循环的方法来做到这一点。

这就是我想出来的。

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

然后只需使用它提供一个数字到零填充:

> zeroPad(50,4);
"0050"

如果数字大于填充,则数字将扩展到超出填充:

> zeroPad(51234, 3);
"51234"

小数也可以!

> zeroPad(51.1234, 4);
"0051.1234"

如果您不介意污染全局命名空间,您可以将其直接添加到 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;
}

如果您希望小数占用填充空间:

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

干杯!



XDR 提出了似乎表现更好的对数变化

警告:如果 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;
}

说到性能,tomsmeding 比较了前 3 个答案 (4 具有对数变化)。 猜猜哪一个主要优于其他两个? :)

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:

> 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.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.

WARNING: This function fails if num equals zero (e.g. 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? :)

野心澎湃 2024-08-06 18:40:40

现代浏览器现在支持 padStart,您可以现在就做:

string.padStart(maxLength, "0");

示例:

string = "14";
maxLength = 5; // maxLength is the max string length, not max # of fills
res = string.padStart(maxLength, "0");
console.log(res); // prints "00014"

number = 14;
maxLength = 5; // maxLength is the max string length, not max # of fills
res = number.toString().padStart(maxLength, "0");
console.log(res); // prints "00014"

Modern browsers now support padStart, you can simply now do:

string.padStart(maxLength, "0");

Example:

string = "14";
maxLength = 5; // maxLength is the max string length, not max # of fills
res = string.padStart(maxLength, "0");
console.log(res); // prints "00014"

number = 14;
maxLength = 5; // maxLength is the max string length, not max # of fills
res = number.toString().padStart(maxLength, "0");
console.log(res); // prints "00014"

后eg是否自 2024-08-06 18:40:40

这是我用来填充最多 7 个字符的数字的方法。

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

这种方法可能适合大多数人。

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

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

编辑2:请注意,从 ES2017 开始,你可以使用 String.prototype.padStart

number.toString().padStart(padding, "0")

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

("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)

Edit 2: Note that since ES2017 you can use String.prototype.padStart:

number.toString().padStart(padding, "0")
一百个冬季 2024-08-06 18:40:40

不幸的是,对于这个问题有很多不必要的复杂建议,通常涉及编写自己的函数来进行数学或字符串操作或调用第三方实用程序。 然而,在基本 JavaScript 库中有一种标准方法只需一行代码即可完成此操作。 将这一行代码包装在函数中可能是值得的,以避免必须指定您永远不想更改的参数,例如本地名称或样式。

var amount = 5;

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

这将产生文本值“005”。 您还可以使用 Number 的 toLocaleString 函数将零填充到小数点右侧。

var amount = 5;

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

这将为文本生成值“5.00”。 将 useGrouping 更改为 true 以对千位使用逗号分隔符。

请注意,将 toLocaleString()localesoptions 参数一起使用 在 ECMA-402 中单独标准化,而不是在 ECMAScript 中。 截至目前,部分浏览器仅实现基本支持 ,即 toLocaleString() 可以忽略任何参数。

完整示例

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.

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.

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.

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.

Complete Example

深海里的那抹蓝 2024-08-06 18:40:40

如果预先知道填充数不超过某个值,则还有另一种方法可以在不循环的情况下执行此操作:

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

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

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/

掩饰不了的爱 2024-08-06 18:40:40

快速但肮脏的方法:

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

对于 x = 5 且 count = 6,您将得到 y = "000005"

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"

淡墨 2024-08-06 18:40:40

ECMAScript 2017:
使用 padStartpadEnd

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

更多信息:

ECMAScript 2017:
use padStart or padEnd

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

More info:

记忆之渊 2024-08-06 18:40:40

这是我想出的一个快速函数来完成这项工作。 如果谁有更简单的方法,欢迎分享!

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

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

    return result;
}

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;
}
剧终人散尽 2024-08-06 18:40:40

我经常使用此构造来临时填充某个值 n,该值已知为正数、小数:

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

其中 offset 是 10^^ 位。

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

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

此十六进制版本稍微详细一些:

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

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

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

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

Where offset is 10^^digits.

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

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

The hexadecimal version of this is slightly more verbose:

(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.

小女人ら 2024-08-06 18:40:40

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

功能:

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

原型:

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

非常简单,我看不出有什么方法可以更简单。 出于某种原因,我在这里多次提到过,人们只是试图不惜一切代价避免“for”和“while”循环。 对于这样一个微不足道的 8 位数字填充,使用正则表达式可能会花费更多的周期。

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.

失眠症患者 2024-08-06 18:40:40

我使用此代码片段来获取五位数字的表示形式:

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

I use this snippet to get a five-digits representation:

(value+100000).toString().slice(-5) // "00123" with value=123
热风软妹 2024-08-06 18:40:40

在所有现代浏览器中,您可以使用

numberStr.padStart(numberLength, "0");

function zeroFill(num, numLength) {
  var numberStr = num.toString();

  return numberStr.padStart(numLength, "0");
}

var numbers = [0, 1, 12, 123, 1234, 12345];

numbers.forEach(
  function(num) {
    var numString = num.toString();
    
    var paddedNum = zeroFill(numString, 5);

    console.log(paddedNum);
  }
);

以下是 MDN 参考 https://developer。 mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart

In all modern browsers you can use

numberStr.padStart(numberLength, "0");

function zeroFill(num, numLength) {
  var numberStr = num.toString();

  return numberStr.padStart(numLength, "0");
}

var numbers = [0, 1, 12, 123, 1234, 12345];

numbers.forEach(
  function(num) {
    var numString = num.toString();
    
    var paddedNum = zeroFill(numString, 5);

    console.log(paddedNum);
  }
);

Here is the MDN reference https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart

恰似旧人归 2024-08-06 18:40:40

数学的力量!

x = 要填充的整数
y = 要填充的零的数量

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

The power of Math!

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

function zeroPad(x, y)
{
   y = Math.max(y-1,0);
   var n = (x / Math.pow(10,y)).toFixed(y);
   return n.replace('.','');  
}
落叶缤纷 2024-08-06 18:40:40

这就是ES6的解决方案。

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

This is the ES6 solution.

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

温柔戏命师 2024-08-06 18:40:40

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

_.padLeft(数字, 6, '0')

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

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

羞稚 2024-08-06 18:40:40

我没有看到任何人指出当您使用 String.prototype.substr() 带有从右侧计数的负数。

OP 问题的单行解决方案(数字 5 的 6 位零填充表示)是:

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

概括我们会得到:

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));

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.

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

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));

攀登最高峰 2024-08-06 18:40:40

不要重新发明轮子; 使用 下划线字符串

< a href="http://jsfiddle.net/plantface/ob6fnh1e/" rel="nofollow noreferrer">jsFiddle

var numToPad = '5';

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

Don't reinvent the wheel; use underscore string:

jsFiddle

var numToPad = '5';

alert(_.str.pad(numToPad, 6, '0')); // Yields: '000005'
瑾兮 2024-08-06 18:40:40

经过很长很长时间的测试,在这个问题的答案中找到了 15 个不同的函数/方法,我现在知道哪个是最好的(最通用和最快)。

我从这个问题的答案中选取了 15 个函数/方法,并制作了一个脚本来测量执行 100 个 pad 所需的时间。 每个填充都会用 2000 零填充数字 9。 这可能看起来有些过分,确实如此,但它让您对函数的缩放有一个很好的了解。

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

您可以自行修改和测试代码。

为了获得最通用的方法,您必须使用循环。 这是因为,如果数量非常多,其他人可能会失败,而这个人会成功。

那么,使用哪个循环呢? 嗯,这将是一个 while 循环。 for 循环仍然很快,但 while 循环稍微快一点(几毫秒) - 而且更干净。

WilcoAleksandar ToplekVitim.us 等答案将完美完成这项工作。

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

我的功能是:

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

您可以在设置填充变量或不设置填充变量的情况下使用我的功能。 就像这样:就

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

个人而言,在我的测试之后,我会使用带有 while 循环的方法,例如 Aleksandar ToplekVitim.us。 不过,我会稍微修改它,以便您能够设置填充字符串。

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

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'

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

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'

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).

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.

The code I used can be found here:
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.

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

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.

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.

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'
尸血腥色 2024-08-06 18:40:40

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

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
}

所以

           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'

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'
﹎☆浅夏丿初晴 2024-08-06 18:40:40

最新的方法要简单得多:

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

output: "02"

The latest way to do this is much simpler:

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

output: "02"

倥絔 2024-08-06 18:40:40

只是另一种解决方案,但我认为它更清晰。

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

  return text;
}

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

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

  return text;
}

甜宝宝 2024-08-06 18:40:40

这个不太原生,但可能是最快的......

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

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;
};
桃扇骨 2024-08-06 18:40:40

我的解决方案

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

用法

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

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

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
桃酥萝莉 2024-08-06 18:40:40

使用 ES6+ JavaScript:

您可以使用类似以下函数的“零填充数字”:

/**
 * @param number The number
 * @param minLength Minimal length for your string with leading zeroes
 * @return Your formatted string
 */
function zerofill(nb, minLength) {
    // Convert your number to string.
    let nb2Str = nb.toString()

    // Guess the number of zeroes you will have to write.
    let nbZeroes = Math.max(0, minLength - nb2Str.length)

    // Compute your result.
    return `${ '0'.repeat(nbZeroes) }${ nb2Str }`
}

console.log(zerofill(5, 6))    // Displays "000005"

使用 ES2017+:

/**
 * @param number The number
 * @param minLength Minimal length for your string with leading zeroes
 * @return Your formatted string
 */
const zerofill = (nb, minLength) => nb.toString().padStart(minLength, '0')

console.log(zerofill(5, 6))    // Displays "000005"

With ES6+ JavaScript:

You can "zerofill a number" with something like the following function:

/**
 * @param number The number
 * @param minLength Minimal length for your string with leading zeroes
 * @return Your formatted string
 */
function zerofill(nb, minLength) {
    // Convert your number to string.
    let nb2Str = nb.toString()

    // Guess the number of zeroes you will have to write.
    let nbZeroes = Math.max(0, minLength - nb2Str.length)

    // Compute your result.
    return `${ '0'.repeat(nbZeroes) }${ nb2Str }`
}

console.log(zerofill(5, 6))    // Displays "000005"

With ES2017+:

/**
 * @param number The number
 * @param minLength Minimal length for your string with leading zeroes
 * @return Your formatted string
 */
const zerofill = (nb, minLength) => nb.toString().padStart(minLength, '0')

console.log(zerofill(5, 6))    // Displays "000005"
风尘浪孓 2024-08-06 18:40:40

您会发现最简单、最直接的解决方案。

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

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;
}
瞳孔里扚悲伤 2024-08-06 18:40:40

使用递归:

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

Use recursion:

function padZero(s, n) {
    s = s.toString(); // In case someone passes a number
    return s.length >= n ? s : padZero('0' + s, n);
}
暮倦 2024-08-06 18:40:40

一些猴子补丁也有效

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"

Some monkeypatching also works

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"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文