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);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…