BigDecimal adding wrong value

后端 未结 5 1968
谎友^
谎友^ 2020-11-27 08:15

I have a BigDecimal defined like this:

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

if i print it, i get the val

5条回答
  •  攒了一身酷
    2020-11-27 09:05

    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).

提交回复
热议问题