如何正确显示价格高达两位小数(分),包括Java中的尾随零?

如何正确显示价格高达两位小数(分),包括Java中的尾随零?

问题描述:

对于Java中的舍入小数有一个很好的问题此处。但是我想知道如何在我的程序中包含尾随零显示价格:$ 1.50,$ 1.00

There is a good question on rounding decimals in Java here. But I was wondering how can I include the trailing zeros to display prices in my program like: $1.50, $1.00

String.format("%.2g%n", 0.912385);

工作正常,但如果位于最后一位小数位,则忽略尾数零。即使我只使用这样的表达式,我的程序出现了这个问题:

works just fine, but omits the trailing zero if it is at the last decimal place. The issue comes up in my program even though I only use expressions like this:

double price = 1.50;

当我以不同的价格(添加,乘法等)进行计算时,结果主要显示为这个:

When I do calculations with different prices (add, multiply, etc.) the result is primarily displayed like this:

$2.5000000000000003

因此,使用String.format可以很好地执行此操作,但是将上述示例截断为

So, using the String.format works fine for this purpose, but it truncates the above example to

$2.5

有没有正确的方式显示第二个小数位后的零点?或者如果计算的输出应为0,则为零或

Is there a proper way to show the trailing zero at the second decimal place? Or both zeros if the output of a calculation should be

$2.00


我建议您这样做:

NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance();
double price = 2.50000000000003;
System.out.println(currencyFormatter.format(price));

这也具有特定于区域设置的优点。例如,如果您在欧元区而不是美国,这将会奏效。

This has the virtue of be locale-specific as well. This will work, for example, if you're in the euro zone instead of the US.