我可以用system。out。print吗?
当前回答
在Java中输出小数点后2位的浮点数:
float f = (float)11/3;
System.out.print(String.format("%.2f",f));
输出:3.67
>使用%。3f表示小数点后三位。
其他回答
看看DecimalFormat
下面是教程中的一个例子:
DecimalFormat myFormatter = new DecimalFormat(pattern);
String output = myFormatter.format(value);
System.out.println(value + " " + pattern + " " + output);
如果你选择像“###”这样的图案。##”,你会得到两位小数点后,我认为值是四舍五入。你会想要查看链接以获得你想要的确切格式(例如,你是否想要后面的零)
float floatValue=22.34555f;
System.out.print(String.format("%.2f", floatValue));
输出是22.35。 如果需要3个小数点,则将其更改为“%.3f”。
你可以使用下面的快速代码,它在最后改变了自己。加上这个点后面有多少个0
float y1 = 0.123456789;
DecimalFormat df = new DecimalFormat("#.00");
y1 = Float.valueOf(df.format(y1));
变量y1之前等于0.123456789。在代码之后,它只会变成0.12。
我建议使用String.format()如果你需要值作为字符串在你的代码。
例如,你可以这样使用String.format():
float myFloat = 2.001f;
String formattedString = String.format("%.02f", myFloat);
试试这个:
private static String getDecimalFormat(double value) {
String getValue = String.valueOf(value).split("[.]")[1];
if (getValue.length() == 1) {
return String.valueOf(value).split("[.]")[0] +
"."+ getValue.substring(0, 1) +
String.format("%0"+1+"d", 0);
} else {
return String.valueOf(value).split("[.]")[0]
+"." + getValue.substring(0, 2);
}
}