0

I want to format a double value into a style of having

  1. Currency Format Symbol
  2. Value rounded into 2 decimal places
  3. Final Value with thousand separator

Specifically using the java.util.Formatter class

Example :-

double amount = 5896324555.59235328;
String finalAmount = "";
// Some coding
System.out.println("Amount is - " + finalAmount);

Should be like :- Amount is - $ 5,896,324,555.60

I searched, but I couldn't understand the Oracle documentations or other tutorials a lot, and I found this link which is very close to my requirement but it's not in Java - How to format double value into string with 2 decimal places after dot and with separators of thousands?

Community
  • 1
  • 1
Praveen Fernando
  • 319
  • 3
  • 13
  • You obviously didn't search enough... There's a lot of questions about Formatter class. See also http://stackoverflow.com/questions/5323502/how-to-set-thousands-separator-in-java about thousand separator.. – Gaël J Dec 29 '15 at 19:55
  • 2
    ...and don't use double for currency. Use BigDecimal. ;) – Jerry Andrews Dec 29 '15 at 19:58
  • @Jerry Andrews any reason in particular? – Praveen Fernando Dec 29 '15 at 20:08
  • 1
    Sure--BigDecimal always gives you infinite precision. float and double operations will introduce rounding errors. The canonical example is always rounding. Consider this article (google's 3rd result on a search for "Java BigDecimal Currency"): https://blogs.oracle.com/CoreJavaTechTips/entry/the_need_for_bigdecimal – Jerry Andrews Jan 07 '16 at 02:02

3 Answers3

10

If you need to use the java.util.Formatter, this will work:

double amount = 5896324555.59235328;
StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb, Locale.US);
formatter.format("$ %(,.2f", amount);
System.out.println("Amount is - " + sb);

Expanded on the sample code from the Formatter page.

Voicu
  • 16,921
  • 10
  • 60
  • 69
3

Instead of using java.util.Formatter, I would strongly suggest using java.text.NumberFormat, which comes with a built-in currency formatter:

double amount = 5896324555.59235328;
NumberFormat formatter = NumberFormat.getCurrencyInstance();
String finalAmount = formatter.format(amount);
System.out.println("Amount is - " + finalAmount); 
// prints: Amount is - $5,896,324,555.59
azurefrog
  • 10,785
  • 7
  • 42
  • 56
3

You could use printf and a format specification like

double amount = 5896324555.59235328;
System.out.printf("Amount is - $%,.2f", amount);

Output is

Amount is - $5,896,324,555.59

To round up to 60 cents, you'd need 59.5 cents (or more).

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249