Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly display a price up to two decimals (cents) including trailing zeros in Java?

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

The simple solution of

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

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

$2.5

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
like image 214
denchr Avatar asked Nov 14 '09 13:11

denchr


1 Answers

I would recommend that you do this:

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.

like image 68
duffymo Avatar answered Sep 18 '22 21:09

duffymo