如何在JavaScript中输出带有前导零的数字? [英] How to output numbers with leading zeros in JavaScript?

查看:90
本文介绍了如何在JavaScript中输出带有前导零的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以将前导零添加到数字前面,从而产生固定长度的字符串?例如,如果我指定2个位置,则5变为"05".

Is there a way to prepend leading zeros to numbers so that it results in a string of fixed length? For example, 5 becomes "05" if I specify 2 places.

推荐答案

注意:可能已过时. ECMAScript 2017包括 String.prototype.padStart

NOTE: Potentially outdated. ECMAScript 2017 includes String.prototype.padStart.

由于数字对于前导零没有意义,因此您必须将数字转换为字符串.像这样:

You'll have to convert the number to a string since numbers don't make sense with leading zeros. Something like this:

function pad(num, size) {
    num = num.toString();
    while (num.length < size) num = "0" + num;
    return num;
}

或者,如果您知道您永远不会使用超过X个零,那么可能会更好.假设您永远不希望超过10位数字.

Or, if you know you'd never be using more than X number of zeros, this might be better. This assumes you'd never want more than 10 digits.

function pad(num, size) {
    var s = "000000000" + num;
    return s.substr(s.length-size);
}

如果您关心负数,则必须去掉-并阅读.

If you care about negative numbers you'll have to strip the - and read it.

这篇关于如何在JavaScript中输出带有前导零的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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