Reputation: 2642
Ok so I have been searching for 2 hours on this and please before jumping to mark this as a duplicate have a look at the question.
I have a number of strings which contain number
Numbers will all be like this
String one = 611960;
String two = 64850;
String three = 0;
String four = 636;
I want to be able to have these in the correct format as in
6,119.60 648.50 0.00 6.36
I have tried
DecimalFormat df = new DecimalFormat("#,###,###,##0.00");
and converting the String to a double e.g.
double amount = Double.parseDouble(one);
which seems to give 611960.0
then I do
String gfeeOne = df.format(amount);
which in turn gives 611,960.00
So at this stage I'm a bit lost. This should be straightforward and maybe I'm getting lost. I want to cover all cases up to something like this 1000000000 e.g. 1,000,000,000.00
Help very much appreciated
Upvotes: 1
Views: 8501
Reputation: 20736
The Strings you have are interpreted as integers, as they don't have any sort of decimal separator in them (which is Locale dependent, be careful about that...). So you basically only have to divide your number by 100, or in other words, move the decimal points to the left by two places.
You should try:
double amount = Double.parseDouble(one)/100.0;
Or, even better, you could free yourself from the problems of basic floating point rounding problems, and use BigDecimal:
BigDecimal amount = new BigDecimal(one).movePointLeft(2);
String gfeeOne = df.format(amount);
Warning if very large values are considered, be sure to use the BigDecimal
, as that preserves the precision, while floating point numbers can lose precision.
Upvotes: 8
Reputation: 69743
You can also use String.Format:
String one = String.Format("%,.2f", (double)611960);
The (double)
will convert the integer value to a floating point value. The format string %,.2f
will turn a floating point number (f
) into a string representation with two decimal points (.2
) and add grouping separators(,
).
Upvotes: 3