ric*_*chs 65 java string-formatting
我需要将十进制值格式化为一个字符串,其中我总是显示至少2位小数,最多4位.
所以例如
"34.49596" would be "34.4959"
"49.3" would be "49.30"
Run Code Online (Sandbox Code Playgroud)
可以使用String.format命令完成吗?或者在java中有更简单/更好的方法来做到这一点.
mos*_*tar 144
是的,你可以这样做String.format
:
String result = String.format("%.2f", 10.0 / 3.0);
// result: "3.33"
result = String.format("%.3f", 2.5);
// result: "2.500"
Run Code Online (Sandbox Code Playgroud)
Ric*_*ell 79
你想要java.text.DecimalFormat.
DecimalFormat df = new DecimalFormat("0.00##");
String result = df.format(34.4959);
Run Code Online (Sandbox Code Playgroud)
Yuv*_*dam 39
这是一个完成工作的小代码片段:
double a = 34.51234;
NumberFormat df = DecimalFormat.getInstance();
df.setMinimumFractionDigits(2);
df.setMaximumFractionDigits(4);
df.setRoundingMode(RoundingMode.DOWN);
System.out.println(df.format(a));
Run Code Online (Sandbox Code Playgroud)