Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
285 views
in Technique[技术] by (71.8m points)

java - 在Java中最多2位小数? [重复](round up to 2 decimal places in java? [duplicate])

This question already has an answer here:

(这个问题在这里已有答案:)

I have read a lot of stackoverflow questions but none seems to be working for me.

(我已经阅读了很多stackoverflow问题,但似乎没有一个对我有用。)

i am using math.round() to round off.

(我正在使用math.round()来完善。)

this is the code:

(这是代码:)

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

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

    System.out.println(roundOff);
}
}

the output i get is: 123 but i want it to be 123.14 .

(我得到的输出是: 123但我希望它是123.14 。)

i read that adding *100/100 will help but as you can see i didn't manage to get it to work.

(我读到添加*100/100会有所帮助但是你可以看到我没有设法让它工作。)

it is absolutely essential for both input and output to be a double.

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

it would be great great help if you change the line 4 of the code above and post it.

(如果您更改上面代码的第4行并发布它将会非常有用。)

  ask by Aayush Mahajan translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Well this one works...

(那么这个有效...)

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

Output is

(输出是)

123.14

Or as @Rufein said

(或者像@Rufein说的那样)

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

this will do it for you as well.

(这也适合你。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...