BigDecimal adding wrong value

早过忘川 提交于 2019-12-17 21:25:56

问题


I have a BigDecimal defined like this:

private static final BigDecimal sd = new BigDecimal(0.7d);

if i print it, i get the value:

0.6999999999999999555910790149937383830547332763671875

which causes some wrong calculations. Does anyone know a way to get the exact value of 0.7 as BigDecimal? Change it to 0.71 would view the right result, but it shouldn't be like that


回答1:


Use a String literal:

private static final BigDecimal sd = new BigDecimal("0.7");

If you use a double, actually public BigDecimal(double val) is called. The reason you do not get 0.7 is that it cannot be exactly represented by a double. See the linked JavaDoc for more information.




回答2:


You should use the declared value in String literal such as new BigDecimal("0.7");




回答3:


Here are three ways:

private static final BigDecimal sd = new BigDecimal("0.7");
private static final BigDecimal sd = new BigDecimal(0.7d, MathContext.DECIMAL32);
private static final BigDecimal sd = new BigDecimal(0.7d, MathContext.DECIMAL64)



回答4:


Perhaps if you bothered to read the documentation, i.e. the javadoc of the constructor you're using, you'd already know the answer.

  1. When a double must be used as a source for a BigDecimal, note that this constructor provides an exact conversion; it does not give the same result as converting the double to a String using the Double.toString(double) method and then using the BigDecimal(String) constructor. To get that result, use the static valueOf(double) method.

When you then look at the javadoc of BigDecimal.valueOf(double), you'll find:

Note: This is generally the preferred way to convert a double (or float) into a BigDecimal, as the value returned is equal to that resulting from constructing a BigDecimal from the result of using Double.toString(double).

So there is your answer: Use BigDecimal.valueOf(0.7d), not new BigDecimal(0.7d).



来源:https://stackoverflow.com/questions/43931672/bigdecimal-adding-wrong-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!