Show a leading zero if a number is less than 10(如果数字小于 10,则显示前导零)
问题描述
可能重复:
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'));
这篇关于如果数字小于 10,则显示前导零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如果数字小于 10,则显示前导零


基础教程推荐
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01