Javascript 如果数字小于 10,则显示前导零
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8089875/
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
Show a leading zero if a number is less than 10
提问by Nicekiwi
Possible Duplicate:
JavaScript equivalent to printf/string.format
How can I create a Zerofilled value using JavaScript?
可能的重复:
JavaScript 等效于 printf/string.format
如何使用 JavaScript 创建一个 Zerofilled 值?
I have a number in a variable:
我在变量中有一个数字:
var number = 5;
I need that number to be output as 05:
我需要将该数字输出为 05:
alert(number); // I want the alert to display 05, rather than 5.
How can I do this?
我怎样才能做到这一点?
I could manually check the number and add a 0 to it as a string, but I was hoping there's a JS function that would do it?
我可以手动检查数字并将 0 作为字符串添加到它,但我希望有一个 JS 函数可以做到这一点?
回答by Chris Fulstow
There's no built-in JavaScript function to do this, but you can write your own fairly easily:
没有内置的 JavaScript 函数可以执行此操作,但您可以相当轻松地编写自己的函数:
function pad(n) {
return (n < 10) ? ("0" + n) : n;
}
EDIT:
编辑:
Meanwhile there is a native JS function that does that. See String#padStart
同时有一个原生的 JS 函数可以做到这一点。见字符串#padStart
console.log(String(5).padStart(2, '0'));
回答by Wazy
Try this
尝试这个
function pad (str, max) {
return str.length < max ? pad("0" + str, max) : str;
}
alert(pad("5", 2));
Example
例子
Or
或者
var number = 5;
var i;
if (number < 10) {
alert("0"+number);
}
Example
例子