I'm turning this double into a string so I can display it on a TextView. I want the string to have 2 decimal places using String.format, but I don't know where to put it in this line of text.
Example.setText(Double.toString(dValue));
Any Ideas?
Example.setText(String.format("%.2f", dValue));
.2
means 2 decimal places f
means it's a decimal type The quick and dirty way is to use a formatted String and specify the number of decimal points. Lately there's been a trend of suggesting the usage of a DecimalFormat
instead since it will respect different locales and the usage of commas or points as a decimal separator.
//The suggested way lately
DecimalFormat formatter = new DecimalFormat("#0.00");
twoDecimals.setText(formatter.format(2.123145));
//The usual way with some caveats
twoDecimals.setText(String.format("%.2f",2.123));
I'm pretty sure it could also be done with formatted strings, but hey.. who am I to go against the trend.
Try this -
DecimalFormat df = new DecimalFormat("#.00");
Example.setText(df.format(dValue));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.