Javascript 使用 jQuery 在数字前添加额外的零?

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

Adding extra zeros in front of a number using jQuery?

javascript

提问by Chill Web Designs

I have file that are uploaded which are formatted like so

我有上传的文件,格式如下

MR 1

MR 2

MR 100

MR 200

MR 300

ETC.

先生 1

先生 2

先生 100

200 先生

先生 300

等等。

What i need to do is add extra two 00s before anything before MR 10 and add one extra 0 before MR10-99

我需要做的是在 MR 10 之前添加额外的两个 00,并在 MR10-99 之前添加一个额外的 0

So files are formatted

所以文件被格式化

MR 001

MR 010

MR 076

ETC.

001先生

010 先生

076 先生

等等。

Any help would be great!

任何帮助都会很棒!

回答by Todd Yandell

Assuming you have those values stored in some strings, try this:

假设您将这些值存储在某些字符串中,请尝试以下操作:

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

pad("3", 3);    // => "003"
pad("123", 3);  // => "123"
pad("1234", 3); // => "1234"

var test = "MR 2";
var parts = test.split(" ");
parts[1] = pad(parts[1], 3);
parts.join(" "); // => "MR 002"

回答by Christopher Thomas

I have a potential solution which I guess is relevent, I posted about it here:

我有一个我认为相关的潜在解决方案,我在这里发布了它:

https://www.facebook.com/antimatterstudios/posts/10150752380719364

https://www.facebook.com/antimatterstudios/posts/10150752380719364

basically, you want a minimum length of 2 or 3, you can adjust how many 0's you put in this piece of code

基本上,您希望最小长度为 2 或 3,您可以调整在这段代码中放入多少个 0

var d = new Date();
var h = ("0"+d.getHours()).slice(-2);
var m = ("0"+d.getMinutes()).slice(-2);
var s = ("0"+d.getSeconds()).slice(-2);

I knew I would always get a single integer as a minimum (cause hour 1, hour 2) etc, but if you can't be sure of getting anything but an empty string, you can just do "000"+d.getHours() to make sure you get the minimum.

我知道我总是会得到一个最小的整数(因为第 1 小时,第 2 小时)等等,但是如果你不能确定得到一个空字符串以外的任何东西,你可以做 "000"+d.getHours( ) 以确保您获得最小值。

then you want 3 numbers? just use -3 instead of -2 in my code, I'm just writing this because I wanted to construct a 24 hour clock in a super easy fashion.

那么你想要3个数字?只需在我的代码中使用 -3 而不是 -2,我写这个只是因为我想以一种超级简单的方式构建一个 24 小时制时钟。

回答by Wilt

Note:see Update 2if you are using latest ECMAScript...

注意:如果您使用的是最新的 ECMAScript,请参阅更新 2...



Here a solution I liked for its simplicity from an answer to a similar question:

这是一个我喜欢的解决方案,因为它很简单,可以回答类似问题

var n = 123

String('00000' + n).slice(-5); // returns 00123
('00000' + n).slice(-5);       // returns 00123


UPDATE

更新

As @RWC suggested you can wrap this of course nicely in a generic function like this:

正如@RWC 建议的那样,您当然可以将其很好地包装在这样的通用函数中:

function leftPad(value, length) { 
    return ('0'.repeat(length) + value).slice(-length); 
}

leftPad(123, 5); // returns 00123

And for those who don't like the slice:

对于那些不喜欢切片的人:

function leftPad(value, length) {
    value = String(value);
    length = length - value.length;
    return ('0'.repeat(length) + value)
}

But if performance matters I recommend reading through the linked answer before choosing one of the solutions suggested.

但是,如果性能很重要,我建议在选择建议的解决方案之一之前通读链接的答案。

UPDATE 2

更新 2

In ES6 the String class now comes with a inbuilt padStartmethod which adds leading characters to a string. Check MDN herefor reference on String.prototype.padStart(). And there is also a padEndmethod for ending characters.

在 ES6 中,String 类现在带有一个内置padStart方法,可以将前导字符添加到字符串中。在此处查看 MDN以供参考String.prototype.padStart()。还有padEnd一种结束字符的方法。

So with ES6 it became as simple as:

所以在 ES6 中它变得如此简单:

var n = 123;
n.padStart(5, '0'); // returns 00123

回答by MadBender

function addLeadingZeros (n, length)
{
    var str = (n > 0 ? n : -n) + "";
    var zeros = "";
    for (var i = length - str.length; i > 0; i--)
        zeros += "0";
    zeros += str;
    return n >= 0 ? zeros : "-" + zeros;
}

//addLeadingZeros (1, 3) =   "001"
//addLeadingZeros (12, 3) =  "012"
//addLeadingZeros (123, 3) = "123"

回答by Davan Etelamaki

This is the function that I generally use in my code to prepend zeros to a number or string.

这是我通常在代码中用于在数字或字符串前添加零的函数。

The inputs are the string or number (str), and the desired length of the output (len).

输入是字符串或数字 (str),以及所需的输出长度 (len)。

var PrependZeros = function (str, len) {
    if(typeof str === 'number' || Number(str)){
    str = str.toString();
    return (len - str.length > 0) ? new Array(len + 1 - str.length).join('0') + str: str;
}
else{
    for(var i = 0,spl = str.split(' '); i < spl.length; spl[i] = (Number(spl[i])&& spl[i].length < len)?PrependZeros(spl[i],len):spl[i],str = (i == spl.length -1)?spl.join(' '):str,i++);
    return str;
}

};

};

Examples:

例子:

PrependZeros('MR 3',3);    // MR 003
PrependZeros('MR 23',3);   // MR 023
PrependZeros('MR 123',3);  // MR 123
PrependZeros('foo bar 23',3);  // foo bar 023

回答by RobG

If you split on the space, you can add leading zeros using a simple function like:

如果在空间上拆分,则可以使用如下简单函数添加前导零:

function addZeros(n) {
  return (n < 10)? '00' + n : (n < 100)? '0' + n : '' + n;
}

So you can test the length of the string and if it's less than 6, split on the space, add zeros to the number, then join it back together.

因此,您可以测试字符串的长度,如果它小于 6,则在空格上拆分,在数字上添加零,然后将其重新连接在一起。

Or as a regular expression:

或者作为正则表达式:

function addZeros(s) {
  return s.replace(/ (\d$)/,' 00').replace(/ (\d\d)$/,' 0');
}

I'm sure someone can do it with one replace, not two.

我敢肯定有人可以通过一次替换而不是两次替换来做到这一点。

Edit - examples

编辑 - 示例

alert(addZeros('MR 3'));    // MR 003
alert(addZeros('MR 23'));   // MR 023
alert(addZeros('MR 123'));  // MR 123
alert(addZeros('foo bar 23'));  // foo bar 023

It will put one or two zeros infront of a number at the end of a string with a space in front of it. It doesn't care what bit before the space is.

它将在字符串末尾的数字前面放一个或两个零,在它前面有一个空格。它不在乎空间之前是什么位。

回答by user2992783

Just for a laugh do it the long nasty way....:
(NOTE: ive not used this, and i would not advise using this.!)

只是为了一笑,用很长的讨厌的方式来做......:(
注意:我没有使用过这个,我不建议使用这个。!)

function pad(str, new_length) {
    ('00000000000000000000000000000000000000000000000000' + str).
    substr((50 + str.toString().length) - new_length, new_length)
}

回答by ShoeMaker

I needed something like this myself the other day, Pud instead of always a 0, I wanted to be able to tell it what I wanted padded ing the front. Here's what I came up with for code:

前几天我自己也需要这样的东西,Pud 而不是总是 0,我希望能够告诉它我想要在前面填充什么。这是我想出的代码:

function lpad(n, e, d) {
  var o = ''; if(typeof(d) === 'undefined'){ d='0'; } if(typeof(e) === 'undefined'){ e=2; }
  if(n.length < e){ for(var r=0; r < e - n.length; r++){ o += d; } o += n; } else { o=n; }
  return o; }

Where n is what you want padded, e is the power you want it padded to (number of characters long it should be), and d is what you want it to be padded with. Seems to work well for what I needed it for, but it would fail if "d" was more than one character long is some cases.

其中 n 是您想要填充的内容,e 是您希望它填充的幂(应该是多少个字符),而 d 是您希望它填充的内容。似乎可以很好地满足我的需要,但在某些情况下,如果“d”的长度超过一个字符,它就会失败。

回答by Amal Kalutotage

str could be a number or a string.

str 可以是数字或字符串。

formatting("hi",3);
function formatting(str,len)
{
   return ("000000"+str).slice(-len);
}

Add more zerosif needs large digits

如果需要大数字,请添加更多

回答by Karthikeyan Baskaran

var str = "43215"; 
console.log("Before : \n string :"+str+"\n Length :"+str.length);
var max = 9;
while(str.length < max ){
                                str = "0" + str;

                        }
console.log("After : \n string :"+str+"\n Length :"+str.length);

It worked for me ! To increase the zeroes, update the 'max' variable

它对我有用!要增加零,请更新“ max”变量

Working Fiddle URL : Adding extra zeros in front of a number using jQuery?:

工作小提琴 URL:使用 jQuery 在数字前添加额外的零?