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

查看:128
本文介绍了如何通过将0添加到一位数字来格式化数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将数字格式化为两位数。当 0 - 9 被传递时,会导致此问题,因此我需要将其格式化为 00 - 09

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.

JavaScript中是否有数字格式化程序?

Is there a number formatter in JavaScript?

推荐答案

我发现的最佳方法如下(请注意,这个简单版本仅适用于正整数):

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小数,你可以使用这个代码(虽然它有点草率)。

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);

最后,如果你有为了处理负数的可能性,最好存储符号,将格式应用于数字的绝对值,并在事后重新应用符号。请注意,此方法不会将数字限制为2位总数。相反,它只限制小数左边的数字(整数部分)。 (确定符号的行在此处找到: javascript中的Number.sign()

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. Instead it only restricts the number to the left of the decimal (the integer part). (The line that determines the sign was found here: Number.sign() in javascript)

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);

这篇关于如何通过将0添加到一位数字来格式化数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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