views:

49

answers:

2

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?

+4  A: 

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

See it on ideone

NullUserException
can you show an example of how I can use NumberFormat with this particular case?
Sheehan Alam
@Sheehan Added code sample
NullUserException
A: 

Once you've converted your String to a number, you can use

// format the number for the default locale
NumberFormat.getInstance().format(num)

or

// format the number for a particular locale
NumberFormat.getInstance(locale).format(num)
Aaron Novstrup