如果数字小于 10,则显示前导零

2022-01-17 00:00:00 math numbers digits javascript

可能重复:
JavaScript 等价于 printf/string.format
如何使用 JavaScript 创建 Zerofilled 值?

我在变量中有一个数字:

I have a number in a variable:

var number = 5;

我需要将该数字输出为 05:

I need that number to be output as 05:

alert(number); // I want the alert to display 05, rather than 5.

我该怎么做?

我可以手动检查数字并将 0 作为字符串添加到其中,但我希望有一个 JS 函数可以做到这一点?

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?

推荐答案

没有内置的 JavaScript 函数可以做到这一点,但您可以相当轻松地编写自己的函数:

There's no built-in JavaScript function to do this, but you can write your own fairly easily:

function pad(n) {
    return (n < 10) ? ("0" + n) : n;
}

<小时>

同时有一个原生 JS 函数可以做到这一点.请参阅 String#padStart

console.log(String(5).padStart(2, '0'));

相关文章