Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
268 views
in Technique[技术] by (71.8m points)

javascript - 如何在JavaScript中输出带有前导零的数字(How to output numbers with leading zeros in JavaScript [duplicate])

Possible Duplicate:

(可能重复:)

I can round to x amount of decimal places with math.round but is there a way to round left of the decimal?

(我可以用math.round舍入到小数位数的x位数,但是有没有办法舍入到小数点左边?)

for example 5 becomes 05 if I specify 2 places

(例如,如果我指定2个位置,则5变为05)

  ask by chris translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

NOTE : Potentially outdated.

(注意 :可能已过时。)

ECMAScript 2017 includes String.prototype.padStart

(ECMAScript 2017包含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;
}

Or if you know you'd never be using more than X number of zeros this might be better.

(或者,如果您知道您永远不会使用超过X个零的数字,那可能会更好。)

This assumes you'd never want more than 10 digits.

(这假设您永远不要超过10位数字。)

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.

(如果您关心负数,则必须去除“-”并读取它。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...