我读过很多关于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行并发布它,将会有很大的帮助。


当前回答

     double d = 2.34568;
     DecimalFormat f = new DecimalFormat("##.00");
     System.out.println(f.format(d));

其他回答

好吧,这个可行……

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

输出是

123.14

或者像@Rufein说的那样

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

这也会对你有帮助。

我只是修改了你的代码。它在我的系统中工作得很好。看看这是否有用

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

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

    System.out.println(roundOff);
}
}
     double d = 2.34568;
     DecimalFormat f = new DecimalFormat("##.00");
     System.out.println(f.format(d));
public static float roundFloat(float in) {
    return ((int)((in*100f)+0.5f))/100f;
}

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

回到你的代码,用100.00替换100,让我知道它是否有效。 然而,如果你想要正式一点,试试这个:

import java.text.DecimalFormat;
DecimalFormat df=new DecimalFormat("0.00");
String formate = df.format(value); 
double finalValue = (Double)df.parse(formate) ;