在java中格式化2个小数位

Jco*_*jer 1 java decimal

这是我的例子:

double num = 0;

num = 4/3;


System.out.println(num);
Run Code Online (Sandbox Code Playgroud)

我的输出是1.0而不是1.3

有什么建议?

Hov*_*els 6

不要进行int除法,因为这总是会导致截断的int.相反,你的部门至少使用一个双倍值.

double num = 4.0/3.0;
Run Code Online (Sandbox Code Playgroud)

然后,当您想要将其显示为String时,请格式化输出,以便您可以选择小数位:

// one way to do it
// %.3f is for a floating number with 3 digits to the right of the decimal
// %n is for new line
System.out.printf(%.3f%n, num); 

Another:
DecimalFormat decimalFormat = new DecimalFormat("0.000");
System.out.println(decimalFormat.format(num));
Run Code Online (Sandbox Code Playgroud)