我将把这个双精度数转换成字符串,以便在TextView上显示。我想要使用String.format使字符串保留2位小数,但我不知道在这行文本中应该放在哪里。
有什么想法吗?
Example.setText(Double.toString(dValue));
有什么想法吗?
Example.setText(Double.toString(dValue));
一种快速且简便的方法是使用格式化字符串并指定小数点位数。最近有一种趋势建议使用 DecimalFormat
,因为它会考虑不同的语言环境和使用逗号或点作为小数分隔符。
//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));
我很确定这也可以用格式化字符串来完成,但是嘿..我又不是要违反潮流。
Example.setText(String.format("%.2f", dValue));
.2
表示保留两位小数f
表示这是一个十进制类型试试这个 -
DecimalFormat df = new DecimalFormat("#.00");
Example.setText(df.format(dValue));