在java中四舍五入到小数点后2位?

2022-08-31 05:30:52

我读过很多堆栈溢出问题,但似乎没有一个对我有用。我用它来四舍五入。这是代码: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);
}
}

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

输入和输出都必须是双精度的。

如果您更改上面代码的第4行并发布它,那将是非常有帮助的。


答案 1

好吧,这个有效...

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

输出为

123.14

或者如@Rufein所说

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

这也将为您完成。


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

推荐