Java BigDecimal使用String构造函数进行错误,以使用ROUND_HALF_UP进行舍入 [英] Java BigDecimal bugs with String constructor to rounding with ROUND_HALF_UP
问题描述
我正在尝试实现一个新的等级舍入到BigDecimal类,我得到一个可能的错误,我可能做错了。下面的代码暴露了我的问题:
I'm trying to implement a new grade rounding to BigDecimal class, and I'm getting a possible bug, must probably I doing something wrong. The code below exposes my problem:
public static void main(String[] args) throws IOException {
BigDecimal valDouble = new BigDecimal(0.35);
valDouble = valDouble.setScale(1, BigDecimal.ROUND_HALF_UP);
System.out.println(valDouble.doubleValue()); // prints 0.3
BigDecimal valString = new BigDecimal(new String("0.35"));
valString = valString.setScale(1, BigDecimal.ROUND_HALF_UP);
System.out.println(valString.doubleValue()); // prints 0.4
}
我的疑问是,BigDecimal与double和String不同构造函数?
My doubt here is, is BigDecimal different for double and String constructors?
我无法理解这个'bug',至少,我只是用一个简单的字符串concat来解决它,如下所示:
I can't understand this 'bug', at least, I just used a simple string concat to 'solve' it, as below:
BigDecimal valDouble = new BigDecimal("" + 0.35);
任何想法可能导致这种奇怪的行为?
Any idea what could be causing this odd behavior?
推荐答案
这不是错误。作为双字面值的0.35表示不完全等于0.35的值;它可能像0.349999995之类的东西。因此它向下舍入。
This isn't a bug. 0.35 as a double literal represents a value that is not exactly equal to 0.35; it's likely something like 0.349999995 or something. So it rounds down.
String构造函数允许您使用0.35精确指定0.35,然后向上舍入。
The String constructor lets you specify 0.35 exactly using "0.35", and that rounds up.
此处不要使用 double
构造函数;当它足够重要使用 BigDecimal
时,你需要远离浮点土地。
Don't use the double
constructor here; when it matters enough to use BigDecimal
you need to stay out of floating-point land.
这篇关于Java BigDecimal使用String构造函数进行错误,以使用ROUND_HALF_UP进行舍入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!