问题
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?
回答1:
String.format("%1$,.2f", myDouble);
回答2:
Use this
NumberFormat format = NumberFormat.getInstance();
format.setMaximumFractionDigits(1);
displayAnswer.setText(format.format(volume)+ " "+outputPref);
回答3:
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));
}
回答4:
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);
回答5:
I hope it will help you
rountdoubel=Maths.round(outputPref)
displayAnswer.setText(volume + " " + rountdoubel);
来源:https://stackoverflow.com/questions/12783015/setting-custom-format-for-numbers-in-textview