This question already has answers here:
How to round a number to n decimal places in Java

(36个答案)


5年前关闭。




我已经阅读了很多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会有所帮助,但是如您所见,我没有设法使其生效。

输入和输出都必须是双倍是绝对必要的。

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

最佳答案

好吧,这个作品...

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

输出为
123.14

或如@Rufein所说
 double roundOff = (double) Math.round(a * 100) / 100;

这也会为您做。

10-07 19:52
查看更多