1

Possible Duplicate:
How do I format a number in java?
String.format() to format double in java

I want to be able to take the output from a double variable (called double) and put it in a TextView along with some String text (called outputPref, which just contains "cubic mm") like below

displayAnswer.setText(volume + " " + outputPref);

This works fine, however, the number shows in the TextView as the full double (with many, many decimal places). I want the number to show with comma's splitting the thousands (if there are any) with one decimal place, like the Excel number format "(* #,##0.0);(* (#,##0.0);(* "-"??);(@_)", or put simply (given I won't have any negative numbers) "#,##0.0"

What is the function I should use to reconfigure the volume double variable before applying it to the TextView?

Community
  • 1
  • 1
Kurt
  • 737
  • 8
  • 23

5 Answers5

4
String.format("%1$,.2f", myDouble);
Blackbelt
  • 152,872
  • 27
  • 286
  • 297
Ashish
  • 13,655
  • 19
  • 73
  • 118
2

Use this

NumberFormat format = NumberFormat.getInstance();
        format.setMaximumFractionDigits(1);
displayAnswer.setText(format.format(volume)+ " "+outputPref);
slezadav
  • 6,076
  • 6
  • 38
  • 61
1

You could round the double number for showing it in the TextView:

double roundTwoDecimals(double d) {
            DecimalFormat twoDForm = new DecimalFormat("#.##");
        return Double.valueOf(twoDForm.format(d));
}
Sebastian Breit
  • 6,109
  • 1
  • 33
  • 53
  • Great. What if I want to have a comma seperating each of the thousands -> i.e. instead of roundTwoDecimals() turning 789455.566 into 789455.57 it would turn it into 789,455.57? – Kurt Oct 08 '12 at 13:53
0

You can set the decimal places with:

DecimalFormat df = new DecimalFormat("#.#");

This will give one decimal place after the whole number, as there is one # symbol after the decimal place.

Then do:

df.format(yourDoubleHere);
ricgeorge
  • 198
  • 3
  • 5
  • 12
0

I hope it will help you

rountdoubel=Maths.round(outputPref)

displayAnswer.setText(volume + " " + rountdoubel);
Blackbelt
  • 152,872
  • 27
  • 286
  • 297
Prashant09
  • 347
  • 3
  • 17