public static void main(String[] args) {
float f1 = 1234.5678f
int f2 = 99900
String f3 = String.format("x=%.2f, y=%.3f", 100.22222f, 200.33333f)
String f4 = String.format("x=%.4f, y=%.5f", 100.22222f, 200.33333f)
System.out.printf("f1 = %.2f\n", f1)
System.out.printf("f2 = %.2f\n", (float)f2)
System.out.printf("f3 = \"%s\"\n", f3)
System.out.printf("f4 = \"%s\"\n", f4)
}
}
输出:
f1 = 1234.57
f2 = 99900.00
f3 = "x=100.22, y=200.333"
f4 = "x=100.2222, y=200.33333"
System.out.println(Double.parseDouble(new
DecimalFormat("#.##").format(a))+ " " +
Double.parseDouble(new DecimalFormat("#.##").format(b)))
把输出语句换成这个就行了。
若出现这种问题,import java.text.DecimalFormat
你没导这个包,导入就可以了。
有两种情况:double x1 = 0.026
System.out.println(String.format("%.2f", x1))
结果:0.03
2、使用数据转换(4种方法)
//方案一:
get_double = (double)(Math.round(result_value*100)/100.0)
//方案二:
DecimalFormat df = new DecimalFormat("#.##")
get_double = Double.ParseDouble(df.format(result_value))
//方案三:
get_double = Double.ParseDouble(String.format("%.2f",result_value))
//方案四:
BigDecimal bd = new BigDecimalresult_value()
BigDecimal bd2 = bd.setScale(2,BigDecimal .ROUND_HALF_UP)
get_double = Double.ParseDouble(bd2.ToString())