英文:
Round up double value in java
问题
我想在Java中对一个双精度浮点数进行向上取整。无论在数学上正确的方式如何,有时候都需要向下舍入该值。例如:
value = 6.5817
我想要向上取整,保留两位小数。因此,我需要该值变成这样:
value = 6.59
这里重要的是始终保留两位小数,并且如果值的小数位数超过两位,则始终向上舍入第二位小数。
有人知道我如何在Java中实现这个吗?
英文:
I want to round up a double value in java. Always to round up the value in ispite that matematecally correct way, sometimes, is round down the value. For example:
value = 6.5817
I want to round up, keeping two decimals. So I need the value will be like this:
value = 6.59
The important thing here is always keep two decimals and always round up the second decimal if the value have more two decimals.
Have someone idea how I can to do this in java?
答案1
得分: 9
由于double
值是不精确的,例如它无法精确存储像0.07
这样的数字,您需要使用BigDecimal
来帮助舍入double
值,以最小的概率获得错误值。
要舍入到小数点后两位,请使用:
double value = 6.5817;
double roundedUp = BigDecimal.valueOf(value).setScale(2, RoundingMode.UP).doubleValue();
System.out.println(roundedUp); // 输出 6.59
请注意,当value = 0.07
时,此代码会打印0.07
,而不像Math.ceil(value * 100.0) / 100.0
那样错误地打印0.08
。
英文:
Since double
values are inexact, e.g. it cannot store a number like 0.07
exactly, you need to use BigDecimal
to help round up a double
value, with the least probability of getting the wrong value.
To round to 2 decimals, use:
double value = 6.5817;
double roundedUp = BigDecimal.valueOf(value).setScale(2, RoundingMode.UP).doubleValue();
System.out.println(roundedUp); // prints 6.59
Note that this code prints 0.07
when value = 0.07
, unlike e.g. Math.ceil(value * 100.0) / 100.0
, which incorrectly prints 0.08
.
答案2
得分: 0
尝试以下内容:
a = 6.5817
Math.ceil(a * 100.0) / 100.0
英文:
Try the following:
double a = 6.5817;
Math.ceil(a * 100.0) / 100.0;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论