Javascript 如何通过在个位数前加 0 来格式化数字?

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

How to format numbers by prepending 0 to single-digit numbers?

javascriptnumber-formatting

提问by Keith Power

I want to format a number to have two digits. The problem is caused when 09is passed, so I need it to be formatted to 0009.

我想将数字格式化为两位数。问题是在0-9传递时引起的,所以我需要将其格式化为00- 09

Is there a number formatter in JavaScript?

JavaScript 中有数字格式化程序吗?

回答by Joseph Marikle

The best method I've found is something like the following:

我发现的最好的方法是这样的:

(Note that this simple version only works for positive integers)

(请注意,这个简单版本仅适用于正整数)

var myNumber = 7;
var formattedNumber = ("0" + myNumber).slice(-2);
console.log(formattedNumber);

For decimals, you could use this code (it's a bit sloppy though).

对于小数,您可以使用此代码(虽然有点草率)。

var myNumber = 7.5;
var dec = myNumber - Math.floor(myNumber);
myNumber = myNumber - dec;
var formattedNumber = ("0" + myNumber).slice(-2) + dec.toString().substr(1);
console.log(formattedNumber);

Lastly, if you're having to deal with the possibility of negative numbers, it's best to store the sign, apply the formatting to the absolute value of the number, and reapply the sign after the fact. Note that this method doesn't restrict the number to 2 total digits. Instead it only restricts the number to the left of the decimal (the integer part). (The line that determines the sign was found here).

最后,如果您必须处理负数的可能性,最好存储符号,将格式应用于数字的绝对值,并在事后重新应用符号。请注意,此方法不会将数字限制为 2 位总位数。相反,它只限制小数点左边的数字(整数部分)。(确定标志的线在这里找到)。

var myNumber = -7.2345;
var sign = myNumber?myNumber<0?-1:1:0;
myNumber = myNumber * sign + ''; // poor man's absolute value
var dec = myNumber.match(/\.\d+$/);
var int = myNumber.match(/^[^\.]+/);

var formattedNumber = (sign < 0 ? '-' : '') + ("0" + int).slice(-2) + (dec !== null ? dec : '');
console.log(formattedNumber);

回答by Rob W

If the number is higher than 9, convert the number to a string (consistency). Otherwise, add a zero.

如果数字大于 9,则将数字转换为字符串(一致性)。否则,添加一个零。

function n(n){
    return n > 9 ? "" + n: "0" + n;
}

n( 9); //Returns "09"
n(10); //Returns "10"
n(999);//Returns "999"

回答by nyteshade

Use the toLocaleString() method in any number. So for the number 6, as seen below, you can get the desired results.

使用任意数量的 toLocaleString() 方法。因此,对于数字 6,如下所示,您可以获得所需的结果。

(6).toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false})

Will generate the string '06'.

将生成字符串'06'。

回答by timrwood

Here's a simple number padding function that I use usually. It allows for any amount of padding.

这是我通常使用的一个简单的数字填充函数。它允许任意数量的填充。

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

Examples:

例子:

leftPad(1, 2) // 01
leftPad(10, 2) // 10
leftPad(100, 2) // 100
leftPad(1, 3) // 001
leftPad(1, 8) // 00000001

回答by Lifehack

In all modern browsers you can use

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

numberStr.padStart(2, "0");

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart

function zeroPad(numberStr) {
  return numberStr.padStart(2, "0");
}

var numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

numbers.forEach(
  function(num) {
    var numString = num.toString();
    
    var paddedNum = zeroPad(numString);

    console.log(paddedNum);
  }
);

回答by Jee Mok

@Lifehack's answer was very useful to me; where I think we can do it in one line for positive numbers

@Lifehack 的回答对我非常有用;我认为我们可以在一行中完成正数

 String(input).padStart(2, '0');

回答by Stark

("0" + (date.getMonth() + 1)).slice(-2);
("0" + (date.getDay())).slice(-2);

回答by fanaur

You can do:

你可以做:

function pad2(number) {
   return (number < 10 ? '0' : '') + number
}

Example:

例子:

document.write(pad2(0) + '<br />');
document.write(pad2(1) + '<br />');
document.write(pad2(2) + '<br />');
document.write(pad2(10) + '<br />');
document.write(pad2(15) + '<br />');

Result:

结果:

00
01
02
10
15

回答by Joe

It seems you might have a string, instead of a number. use this:

看起来你可能有一个字符串,而不是一个数字。用这个:

var num = document.getElementById('input').value,
    replacement = num.replace(/^(\d)$/, '0');
document.getElementById('input').value = replacement;

Here's an example: http://jsfiddle.net/xtgFp/

这是一个例子:http: //jsfiddle.net/xtgFp/

回答by pwuk

Quick and dirty one liner....

快速而肮脏的一个班轮......

function zpad(n, len) {
  return 0..toFixed(len).slice(2,-n.toString().length)+n.toString();
}