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
373 views
in Technique[技术] by (71.8m points)

javascript - 如何通过将0添加到一位数字来格式化数字?(How to format numbers by prepending 0 to single-digit numbers?)

I want to format a number to have two digits.(我想格式化一个数字有两位数。)

The problem is caused when 09 is passed, so I need it to be formatted to 0009 .(当0 - 9通过时会导致问题,所以我需要将其格式化为00 - 09 。) Is there a number formatter in JavaScript?(JavaScript中是否有数字格式化程序?)   ask by Keith Power translate from so

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

1 Reply

0 votes
by (71.8m points)

The best method I've found is something like the following:(我发现的最佳方法如下:)

(Note that this simple version only works for positive integers)((请注意,此简单版本仅适用于正整数)) var myNumber = 7; var formattedNumber = ("0" + myNumber).slice(-2); console.log(formattedNumber); For decimals, you could use this code (it's a bit sloppy though).(对于小数,您可以使用此代码(虽然它有点草率)。) var myNumber = 7.5; var dec = myNumber - Math.floor(myNumber); myNumber = myNumber - dec; var formattedNumber = ("0" + myNumber).slice(-2) + dec.toString().substr(1); console.log(formattedNumber); Lastly, if you're having to deal with the possibility of negative numbers, it's best to store the sign, apply the formatting to the absolute value of the number, and reapply the sign after the fact.(最后,如果您必须处理负数的可能性,最好存储符号,将格式应用于数字的绝对值,然后在事后重新应用符号。) Note that this method doesn't restrict the number to 2 total digits.(请注意,此方法不会将数字限制为2位总数。) Instead it only restricts the number to the left of the decimal (the integer part).(相反,它只限制小数左边的数字(整数部分)。) (The line that determines the sign was found here ).((确定符号的行在这里找到)。) var myNumber = -7.2345; var sign = myNumber?myNumber<0?-1:1:0; myNumber = myNumber * sign + ''; // poor man's absolute value var dec = myNumber.match(/\.\d+$/); var int = myNumber.match(/^[^\.]+/); var formattedNumber = (sign < 0 ? '-' : '') + ("0" + int).slice(-2) + (dec !== null ? dec : ''); console.log(formattedNumber);

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

1.4m articles

1.4m replys

5 comments

57.0k users

...