3

这是我的例子:

double num = 0;

num = 4/3;


System.out.println(num);

我的输出是 1.0 而不是 1.3

有什么建议么?

4

4 回答 4

8

不要进行 int 除法,因为这总是会导致截断的 int。而是让您的部门至少使用一个双精度值。

double num = 4.0/3.0;

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

// 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));
于 2012-10-02T02:47:33.337 回答
1

num=(double)4/3;

它会返回1.3333....然后你可以四舍五入小数

于 2021-01-28T09:08:24.603 回答
0

您还应该使用 String.format(%1.2f, yourDouble) 来格式化小数位

于 2012-10-02T02:51:08.793 回答
0

试试这个..

double value= 255.956666;

BigDecimal bd = new BigDecimal(value).setScale(2, RoundingMode.HALF_UP);
System.out.println("value="+bd);
于 2015-05-27T17:52:19.253 回答