在java中四舍五入到小数点后2位? [英] round up to 2 decimal places in java?
本文介绍了在java中四舍五入到小数点后2位?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经阅读了很多 stackoverflow 问题,但似乎没有一个对我有用.我正在使用 math.round()
来四舍五入.这是代码:
I have read a lot of stackoverflow questions but none seems to be working for me. i am using math.round()
to round off.
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);
}
}
我得到的输出是:123
但我希望它是 123.14
.我读到添加 *100/100
会有所帮助,但正如你所看到的,我没有设法让它工作.
the output i get is: 123
but i want it to be 123.14
. i read that adding *100/100
will help but as you can see i didn't manage to get it to work.
输入和输出都是双精度是绝对必要的.
it is absolutely essential for both input and output to be a double.
如果您更改上面代码的第 4 行并发布它,将会有很大帮助.
it would be great great help if you change the line 4 of the code above and post it.
推荐答案
这个很好用...
double roundOff = Math.round(a * 100.0) / 100.0;
输出是
123.14
或者如@Rufein所说
Or as @Rufein said
double roundOff = (double) Math.round(a * 100) / 100;
这也适用于您.
这篇关于在java中四舍五入到小数点后2位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文