我如何格式化一个整数到一个特定的长度在JavaScript? [英] How can I format an integer to a specific length in javascript?
问题描述
if(num <10)num =000+ num;
else if(num <100)num =00+ num;
else if(num <1000)num =0+ num;
我想要一些内建在Javascript中的东西,但我似乎找不到任何东西。我不认为有什么内置到JavaScript语言来做到这一点。这是一个简单的函数:
$ p $ 函数FormatNumberLength(num,length){
var r =+ NUM;
while(r.length
}
return r;
FormatNumberLength(10000,5)输出'10000'
FormatNumberLength(1000,5)输出'01000'
FormatNumberLength(100,5 )输出'00100'
FormatNumberLength(10,5)输出'00010'
I have a number in Javascript, that I know is less than 10000 and also non-negative. I want to display it as a four-digit number, with leading zeroes. Is there anything more elegant than the following?
if(num<10) num="000"+num;
else if(num<100) num="00"+num;
else if(num<1000) num="0"+num;
I want something that is built into Javascript, but I can't seem to find anything.
I don't think there's anything "built" into the JavaScript language for doing this. Here's a simple function that does this:
function FormatNumberLength(num, length) {
var r = "" + num;
while (r.length < length) {
r = "0" + r;
}
return r;
}
FormatNumberLength(10000, 5) outputs '10000'
FormatNumberLength(1000, 5) outputs '01000'
FormatNumberLength(100, 5) outputs '00100'
FormatNumberLength(10, 5) outputs '00010'
这篇关于我如何格式化一个整数到一个特定的长度在JavaScript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!