Praveen Fernando
Praveen Fernando

Reputation: 329

How to format a double into thousand separated and 2 decimals using java.util.Formatter

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?

Upvotes: 0

Views: 11410

Answers (4)

vuhoanghiep1993
vuhoanghiep1993

Reputation: 881

You can user

NumberFormat usFormatter = NumberFormat.getNumberInstance(new Locale("en", "US"));
usFormatter.setMaximumFractionDigits(2);
usFormatter.setMinimumFractionDigits(2);
formattedAmount = String.format("%s", usFormatter.format(value.doubleValue()));

123456789.123456 -> 123,456,789.12

123456789.9878 -> 123,456,789.99

Upvotes: 0

Voicu
Voicu

Reputation: 17870

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.

Upvotes: 10

azurefrog
azurefrog

Reputation: 10955

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

Upvotes: 3

Elliott Frisch
Elliott Frisch

Reputation: 201537

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).

Upvotes: 3

Related Questions