java计算结果 小数点后保留两位

Python015

java计算结果 小数点后保留两位,第1张

System.out.println(Double.parseDouble(new

DecimalFormat("#.##").format(a))+ "  " +

Double.parseDouble(new DecimalFormat("#.##").format(b)))

把输出语句换成这个就行了。

若出现这种问题,import java.text.DecimalFormat

你没导这个包,导入就可以了。

public class Main {

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"