在Java中将双精度值向上取整。

huangapple go评论83阅读模式
英文:

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;

huangapple
  • 本文由 发表于 2020年8月28日 04:44:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/63623923.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定