Ste*_*fza 3 java string android type-conversion android-studio
我正在将这个双精度数转换为字符串,以便可以将其显示在 TextView 上。我希望使用 String.format 使字符串具有 2 个小数位,但我不知道将其放在这行文本中的何处。
Example.setText(Double.toString(dValue));
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
快速但肮脏的方法是使用格式化字符串并指定小数点位数。最近有一种趋势是建议使用 aDecimalFormat代替,因为它将尊重不同的区域设置以及使用逗号或点作为小数分隔符。
//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));
Run Code Online (Sandbox Code Playgroud)
我很确定它也可以用格式化字符串来完成,但是嘿..我是谁来逆潮流而行。