[英]Formatting numbers using DecimalFormat
I am trying to format prices using DecimalFormat, but this isn't working for all variations.我正在尝试使用 DecimalFormat 格式化价格,但这不适用于所有变体。
DecimalFormat df = new DecimalFormat("0.##")
df.format(7.8)
df.format(85.0)
prints印刷
7.80
and和
85
but "7.79999" gets formatted as "7.8", not "7.80".但是“7.79999”被格式化为“7.8”,而不是“7.80”。 I have tried doing things this way
我试过这样做
DecimalFormat df = new DecimalFormat("0.00")
to force two dp, but then "85.0" gets formatted as "85.00" not "85"!强制两个 dp,但随后“85.0”被格式化为“85.00”而不是“85”!
Is there a way of capturing all variations, so that prices are printed either as #, ##, or #.##?有没有办法捕获所有变化,以便将价格打印为 #、## 或 #.##? For example:
例如:
5, 55, 5.55, 5.50, 500, 500.40
5, 55, 5.55, 5.50, 500, 500.40
There is a slight difference between these two formats.这两种格式略有不同。 The "#.##" means it will print the number with maximum two decimal places whereas "#.00" means it will always display two decimal places and if the decimal places are less than two, it will replace them with zeros.
“#.##”表示将打印最多两位小数,而“#.00”表示将始终显示两位小数,如果小数位小于两位,它将用零替换。 see the example below with output.
请参阅下面的示例和输出。
public static final DecimalFormat df1 = new DecimalFormat( "#.##" );
public static final DecimalFormat df2 = new DecimalFormat( "#.00" );
System.out.println(df1.format(7.80));
System.out.println(df1.format(85));
System.out.println(df1.format(85.786));
System.out.println(df2.format(7.80));
System.out.println(df2.format(85));
System.out.println(df2.format(85.786));
And the output will be输出将是
7.8
85
85.79
7.80
85.00
85.79
This doesn't seem to be solved by a single formatter
.这似乎不能由单个
formatter
解决。 I suggest you use "0.00"
format and replace ".00"
with an empty string.我建议您使用
"0.00"
格式并将".00"
替换为空字符串。
public static String myFormat(double number) {
DecimalFormat df = new DecimalFormat("0.00");
return df.format(number).replaceAll("\\.00$", "");
}
I don't think it's possible, at least not with Java SE formatters.我认为这是不可能的,至少对于 Java SE 格式化程序来说是不可能的。 You need to make a custom formatter.
您需要制作自定义格式化程序。 I would do it like this
我会这样做
String res = df.format(number).replace(".00", "");
Use the BigDecimal number class instead:改用 BigDecimal 数字类:
eg if n is a BigDecimal, then you can use例如,如果 n 是 BigDecimal,那么您可以使用
String s = NumberFormat.getCurrencyInstance().format(n);
By the way, it's best practice to use BigDecimal when working with money.顺便说一下,最好的做法是在处理金钱时使用 BigDecimal。
您可以尝试:
DecimalFormat df = new DecimalFormat("#.##",new DecimalFormatSymbols(Locale.US));
System.out.println(new java.text.DecimalFormat("#.##").format(5.00));
This will print 5这将打印 5
System.out.println(new java.text.DecimalFormat("#.00").format(500.401));
This will print 500.40这将打印 500.40
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.