如何正确显示价格高达两位小数(分),包括Java中的尾随零? [英] How to properly display a price up to two decimals (cents) including trailing zeros in Java?

查看:143
本文介绍了如何正确显示价格高达两位小数(分),包括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.

这篇关于如何正确显示价格高达两位小数(分),包括Java中的尾随零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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