我读过很多关于stackoverflow的问题,但似乎没有一个对我有用。我使用math.round()来四舍五入。 这是代码:

class round{
    public static void main(String args[]){

    double a = 123.13698;
    double roundOff = Math.round(a*100)/100;

    System.out.println(roundOff);
}
}

我得到的输出是:123,但我希望它是123.14。我读到添加*100/100会有帮助,但正如你所看到的,我没有设法让它工作。

输入和输出都是double是绝对必要的。

如果您更改上面代码的第4行并发布它,将会有很大的帮助。


当前回答

似乎你被整数算术击中了:在某些语言中(int)/(int)总是被计算为整数算术。 为了强制浮点运算,确保至少有一个操作数是非整数:

double roundOff = Math.round(a*100)/100.f;

其他回答

BigDecimal a = new BigDecimal("123.13698");
BigDecimal roundOff = a.setScale(2, BigDecimal.ROUND_HALF_EVEN);
System.out.println(roundOff);

试一试:

class round{
public static void main(String args[]){

double a = 123.13698;
double roundOff = Math.round(a*100)/100;
String.format("%.3f", roundOff); //%.3f defines decimal precision you want
System.out.println(roundOff);   }}

似乎你被整数算术击中了:在某些语言中(int)/(int)总是被计算为整数算术。 为了强制浮点运算,确保至少有一个操作数是非整数:

double roundOff = Math.round(a*100)/100.f;
public static float roundFloat(float in) {
    return ((int)((in*100f)+0.5f))/100f;
}

在大多数情况下应该没问题。例如,如果您希望与double类型兼容,您仍然可以更改类型。

double roundOff = Math.round(a*100)/100;

应该是

double roundOff = Math.round(a*100)/100D;

将'D'添加到100使其成为双字面量,因此产生的结果将具有精度