如何在JavaScript中输出带前导零的整数 [英] How to output integers with leading zeros in JavaScript

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

问题描述


可能重复:

我可以用math.round舍入到x的小数位数但是有没有办法绕小数点左边?例如,如果我指定2个位置,则5变为05

I can round to x amount of decimal places with math.round but is there a way to round left of the decimal? 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're asking for zero padding? Not really rounding. You'll have to convert it to a string since numbers don't make sense with leading zeros. Something like this...

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

或者如果你知道你永远不会使用超过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 readd it.

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

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