在 JavaScript 中用前导零填充数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10073699/
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 23:44:04  来源:igfitidea点击:

Pad a number with leading zeros in JavaScript

javascriptformatting

提问by Nate Pet

In JavaScript, I need to have padding.

在 JavaScript 中,我需要填充。

For example, if I have the number 9, it will be "0009". If I have a number of say 10, it will be "0010". Notice how it will always contain four digits.

例如,如果我有数字 9,它将是“0009”。如果我有一个数字说 10,它将是“0010”。请注意它如何始终包含四位数字。

One way to do this would be to subtract the number minus 4 to get the number of 0s I need to put.

一种方法是减去负 4 的数字以获得我需要放置的 0 的数量。

Is there was a slicker way of doing this?

有没有更巧妙的方法来做到这一点?

回答by Pointy

Not a lot of "slick" going on so far:

到目前为止还没有很多“光滑”:

function pad(n, width, z) {
  z = z || '0';
  n = n + '';
  return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}

When you initialize an array with a number, it creates an array with the lengthset to that value so that the array appears to contain that many undefinedelements. Though some Array instance methods skip array elements without values, .join()doesn't, or at least not completely; it treats them as if their value is the empty string. Thus you get a copy of the zero character (or whatever "z" is) between each of the array elements; that's why there's a + 1in there.

当您使用数字初始化数组时,它会创建一个数组,该数组length设置为该值,以便该数组看起来包含那么多undefined元素。尽管一些 Array 实例方法会跳过没有值的数组元素,.join()但不会或至少不会完全跳过;它将它们视为它们的值是空字符串。因此,您会在每个数组元素之间获得零字符(或任何“z”)的副本;这就是为什么那里有一个+ 1

Example usage:

用法示例:

pad(10, 4);      // 0010
pad(9, 4);       // 0009
pad(123, 4);     // 0123

pad(10, 4, '-'); // --10

回答by Robin Whittleton

function padToFour(number) {
  if (number<=9999) { number = ("000"+number).slice(-4); }
  return number;
}

Something like that?

类似的东西?

Bonus incomprehensible-but-slicker single-line ES6 version:

额外的难以理解但更流畅的单行 ES6 版本:

let padToFour = number => number <= 9999 ? `000${number}`.slice(-4) : number;

ES6isms:

ES6主义:

  • letis a block scoped variable (as opposed to var's functional scoping)
  • =>is an arrow function that among other things replaces functionand is prepended by its parameters
  • If a arrow function takes a single parameter you can omit the parentheses (hence number =>)
  • If an arrow function body has a single line that starts with returnyou can omit the braces and the returnkeyword and simply use the expression
  • To get the function body down to a single line I cheated and used a ternary expression
  • let是一个块作用域变量(与var的功能作用域相反)
  • =>是一个箭头函数,除其他外function,它会替换并附加其参数
  • 如果箭头函数采用单个参数,则可以省略括号(因此number =>
  • 如果箭头函数体有一行以开头,return您可以省略大括号和return关键字,只需使用表达式
  • 为了将函数体缩减为一行,我欺骗并使用了三元表达式

回答by diEcho

Try:

尝试:

String.prototype.lpad = function(padString, length) {
    var str = this;
    while (str.length < length)
        str = padString + str;
    return str;
}

Now test:

现在测试:

var str = "5";
alert(str.lpad("0", 4)); //result "0005"
var str = "10"; // note this is string type
alert(str.lpad("0", 4)); //result "0010"

DEMO

DEMO



In ECMAScript 8, we have new method padStartand padEndwhich has below syntax.

ECMAScript 8 中,我们有新的方法padStartpadEnd其语法如下。

'string'.padStart(targetLength [,padString]):

'string'.padStart(targetLength [,padString]):

So now we can use

所以现在我们可以使用

const str = "5";
str.padStart(4, '0'); // '0005'

回答by Peter C

Funny, I recently had to do this.

有趣的是,我最近不得不这样做。

function padDigits(number, digits) {
    return Array(Math.max(digits - String(number).length + 1, 0)).join(0) + number;
}

Use like:

像这样使用:

padDigits(9, 4);  // "0009"
padDigits(10, 4); // "0010"
padDigits(15000, 4); // "15000"

Not beautiful, but effective.

不漂亮,但有效。

回答by kennebec

You did say you had a number-

你确实说过你有一个号码——

String.prototype.padZero= function(len, c){
    var s= '', c= c || '0', len= (len || 2)-this.length;
    while(s.length<len) s+= c;
    return s+this;
}
Number.prototype.padZero= function(len, c){
    return String(this).padZero(len,c);
}

回答by Robert Messerle

You could do something like this:

你可以这样做:

function pad ( num, size ) {
  return ( Math.pow( 10, size ) + ~~num ).toString().substring( 1 );
}

Edit: This was just a basic idea for a function, but to add support for larger numbers (as well as invalid input), this would probably be better:

编辑:这只是一个函数的基本思想,但要添加对更大数字(以及无效输入)的支持,这可能会更好:

function pad ( num, size ) {
  if (num.toString().length >= size) return num;
  return ( Math.pow( 10, size ) + Math.floor(num) ).toString().substring( 1 );
}

This does 2 things:

这有两件事:

  1. If the number is larger than the specified size, it will simply return the number.
  2. Using Math.floor(num)in place of ~~numwill support larger numbers.
  1. 如果数字大于指定的大小,它将简单地返回数字。
  2. 使用Math.floor(num)代替~~num将支持更大的数字。

回答by xxbbcc

This is not really 'slick' but it's faster to do integer operations than to do string concatenations for each padding 0.

这不是真正的“slick”,但执行整数运算比为每个 padding 执行字符串连接更快0

function ZeroPadNumber ( nValue )
{
    if ( nValue < 10 )
    {
        return ( '000' + nValue.toString () );
    }
    else if ( nValue < 100 )
    {
        return ( '00' + nValue.toString () );
    }
    else if ( nValue < 1000 )
    {
        return ( '0' + nValue.toString () );
    }
    else
    {
        return ( nValue );
    }
}

This function is also hardcoded to your particular need (4 digit padding), so it's not generic.

此函数也根据您的特定需求进行了硬编码(4 位填充),因此它不是通用的。

回答by Phrogz

For fun, instead of using a loop to create the extra zeros:

为了好玩,而不是使用循环来创建额外的零:

function zeroPad(n,length){
  var s=n+"",needed=length-s.length;
  if (needed>0) s=(Math.pow(10,needed)+"").slice(1)+s;
  return s;
}

回答by DashK

Since you mentioned it's always going to have a length of 4, I won't be doing any error checking to make this slick. ;)

既然你提到它的长度总是 4,我不会做任何错误检查来使这个变得流畅。;)

function pad(input) {
    var BASE = "0000";
    return input ? BASE.substr(0, 4 - Math.ceil(input / 10)) + input : BASE;
}

Idea: Simply replace '0000' with number provided... Issue with that is, if inputis 0, I need to hard-code it to return '0000'. LOL.

想法:简单地用提供的数字替换“0000”......问题是,如果input是 0,我需要对其进行硬编码以返回“0000”。哈哈。

This should be slick enough.

这应该足够光滑。

JSFiddler: http://jsfiddle.net/Up5Cr/

JSFiddler:http: //jsfiddle.net/Up5Cr/