javascript 在Javascript中将零填充到数字的左侧
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25198968/
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
Padding zero to the left of number in Javascript
提问by David
I have a ten digit number that will always be constant. I want to pad it so, that it will always remove a zero for every extra number added to the number. Can someone please show me an example of how I can do this?
我有一个永远不变的十位数字。我想填充它,以便它始终为添加到数字的每个额外数字删除一个零。有人可以向我展示我如何做到这一点的例子吗?
eg. 0000000001
例如。0000000001
0000000123
0000011299
回答by Rahul Tripathi
You can use this function:
您可以使用此功能:
function pad (str, max) {
str = str.toString();
return str.length < max ? pad("0" + str, max) : str;
}
Output
输出
pad("123", 10); // => "0000000123"
回答by hsz
Just try with:
只需尝试:
function zeroPad(input, length) {
return (Array(length + 1).join('0') + input).slice(-length);
}
var output = zeroPad(123, 10);
Output:
输出:
"0000000123"
回答by Ferdi265
Another variant would be:
另一种变体是:
function pad(input, length) {
return Array(length - Math.floor(Math.log10(input))).join('0') + input;
}
var out = pad(23, 4); // is "0023"