Javascript 格式化一个数字,长度正好是两个?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5774042/
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
Format a Number, Exactly Two in Length?
提问by John R
I have an integer that is less then 100 and is printed to an HTML page with JavaScript. How do I format the integer so that it is exactly two digits long? For example:
我有一个小于 100 的整数,并使用 JavaScript 打印到 HTML 页面。如何格式化整数,使其正好是两位数长?例如:
01
02
03
...
09
10
11
12
...
01
02
03
...
09
10
11
12
...
回答by Chris Nielsen
function pad(d) {
return (d < 10) ? '0' + d.toString() : d.toString();
}
pad(1); // 01
pad(9); // 09
pad(10); // 10
回答by Jigish Chawda
String("0" + x).slice(-2);
where x
is your number.
x
你的号码在哪里。
回答by liubiantao
回答by Fabianius
Just use the following short function to get the result you need:
只需使用以下简短函数即可获得所需的结果:
function pad2(number) {
return (number < 10 ? '0' : '') + number
}
回答by StanleyH
A direct way to pad a number to the left in Javascript is to calculate the number of digits by log base 10. For example:
在 Javascript 中向左填充数字的直接方法是通过对数基数 10 计算位数。例如:
function padLeft(positiveInteger, totalDigits) {
var padding = "00000000000000";
var rounding = 1.000000000001;
var currentDigits = positiveInteger > 0 ? 1 + Math.floor(rounding * (Math.log(positiveInteger) / Math.LN10)) : 1;
return (padding + positiveInteger).substr(padding.length - (totalDigits - currentDigits));
}
The rounding factor fixes the problem that there is no way to get an exact log of powers of 10, for example Math.log(1000) / Math.LN10 == 2.9999999999999996 Of course one should add validation of the parameters.
舍入因子解决了无法获得 10 次幂的精确对数的问题,例如 Math.log(1000) / Math.LN10 == 2.99999999999999996 当然应该添加参数验证。
回答by MJB
// Return a string padded
function FormatMe(n) {
return (n<10) ? '0'+n : n;
}
回答by ucpwang
function padLeft(a, b) {
var l = (a + '').length;
if (l >= b) {
return a + '';
} else {
var arr = [];
for (var i = 0; i < b - l ;i++) {
arr.push('0');
}
arr.push(a);
return arr.join('');
}
}
回答by Salem Chen
I use regex to format my time such as
我使用正则表达式来格式化我的时间,例如
const str = '12:5'
const str = '12:5'
const final = str.replace(/\d+/g, (match, offset, string) => match < 10 ? '0' + match : match)
const final = str.replace(/\d+/g, (match, offset, string) => match < 10 ? '0' + match : match)
output: 12:05
输出:12:05
回答by Kit sune
I usually use this function.
我通常使用这个功能。
function pad(n, len) {
let l = Math.floor(len)
let sn = '' + n
let snl = sn.length
if(snl >= l) return sn
return '0'.repeat(l - snl) + sn
}
Usage Example
使用示例
pad(1, 1) // ==> returns '1' (string type)
pad(384, 5) // ==> returns '00384'
pad(384, 4.5)// ==> returns '0384'
pad(5555, 2) // ==> returns '5555'
回答by Penny Liu
Improved version of previous answer:
先前答案的改进版本:
var result = [...Array(12)].map((_, i) => zeroFill(i + 1, 2));
function zeroFill(num, size) {
let s = num + '';
while (s.length < size) s = `0${s}`;
return s;
}
console.log(result)