简体   繁体   English

Java,将小数点后两位取整

[英]Java, rounding a double to two decimal places

I'm trying to round a double to the nearest two decimal places however, it is just rounding to the nearest full number. 我正在尝试将双精度四舍五入到最接近的两位小数,但是,它只是四舍五入到最接近的整数。

For example, 19634.0 instead of 19634.95. 例如,用19634.0代替19634.95。

This is the current code I use for the rounding 这是我用于四舍五入的当前代码

double area = Math.round(Math.PI*Radius()*Radius()*100)/100;

I can't see where i am going wrong. 我看不到我要去哪里错了。

Many thanks for any help. 非常感谢您的帮助。

Well, Math.round(Math.PI*Radius()*Radius()*100) is long . 好吧, Math.round(Math.PI*Radius()*Radius()*100)long 100 is int . 100int

So Math.round(Math.PI*Radius()*Radius()*100) / 100 will become long ( 19634 ). 因此Math.round(Math.PI*Radius()*Radius()*100) / 100将变long19634 )。

Change it to Math.round(Math.PI*Radius()*Radius()*100) / 100.0 . 将其更改为Math.round(Math.PI*Radius()*Radius()*100) / 100.0 100.0 is double , and the result will also be double ( 19634.95 ). 100.0double ,结果也将是double19634.95 )。

Do you actually want want to round the value to 2 places, which will cause snowballing rounding errors in your code, or simply display the number with 2 decimal places? 您是否真的想将值舍入到2位,这会导致代码中滚雪球的舍入错误,或者仅显示2位小数? Check out String.format() . String.format()String.format() Complex but very powerful. 复杂但功能强大。

You can use a DecimalFormat object: 您可以使用DecimalFormat对象:

DecimalFormat df = new DecimalFormat ();
df.setMaximumFractionDigits (2);
df.setMinimumFractionDigits (2);

System.out.println (df.format (19634.95));

You might want to take a look at the DecimalFormat class. 您可能想看看DecimalFormat类。

double x = 4.654;

DecimalFormat twoDigitFormat = new DecimalFormat("#.00");
System.out.println("x=" + twoDigitFormat.format());

This gives "x=4.65". 这给出“ x = 4.65”。 The difference between # and 0 in the pattern is that the zeros are always displayed and # will not if the last ones are 0. 模式中的#0之间的区别在于,始终显示零,如果最后一个为0,则#不会显示。

The following example came from this forum , but seems to be what you are looking for. 以下示例来自该论坛 ,但似乎正是您想要的。

 double roundTwoDecimals(double d) {
      DecimalFormat twoDForm = new DecimalFormat("#.##");
      return Double.valueOf(twoDForm.format(d));
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM