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,则显示前导零


- addEventListener 在 IE 11 中不起作用 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- 失败的 Canvas 360 jquery 插件 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01