How can I format a String number to have commas and round?

Sheehan Alam picture Sheehan Alam · Sep 9, 2010 · Viewed 228.8k times · Source

What is the best way to format the following number that is given to me as a String?

String number = "1000500000.574" //assume my value will always be a String

I want this to be a String with the value: 1,000,500,000.57

How can I format it as such?

Answer

NullUserException picture NullUserException · Sep 9, 2010

You might want to look at the DecimalFormat class; it supports different locales (eg: in some countries that would get formatted as 1.000.500.000,57 instead).

You also need to convert that string into a number, this can be done with:

double amount = Double.parseDouble(number);

Code sample:

String number = "1000500000.574";
double amount = Double.parseDouble(number);
DecimalFormat formatter = new DecimalFormat("#,###.00");

System.out.println(formatter.format(amount));