我如何格式化一个整数到一个特定的长度在JavaScript? [英] How can I format an integer to a specific length in javascript?

查看:136
本文介绍了我如何格式化一个整数到一个特定的长度在JavaScript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Javascript的数字,我知道是不到10000,也是非负面的。我想显示它作为一个四位数字,与前导零。有什么比以下更优雅?

  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 r =0+ r;
}
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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆