0

The situation is like this, the expected result through the following code is 123.10 is actually 123.09, for this result is a bit ignorant, ROUND_DOWN is not truncated, why is there a calculation, 123.2000 will be truncated to 123.20, what is the principle? jdk1.8

public static void main(String[] args){
    BigDecimal b = new BigDecimal(123.1000);
    System.out.println(b.setScale(2, BigDecimal.ROUND_DOWN));
}

123.09

Process finished with exit code 0

JonK
  • 2,097
  • 2
  • 25
  • 36
fi5
  • 1

1 Answers1

0

You're using the BigDecimal(double) constructor, the documentation for which states:

The results of this constructor can be somewhat unpredictable. One might assume that writing new BigDecimal(0.1) in Java creates a BigDecimal which is exactly equal to 0.1 (an unscaled value of 1, with a scale of 1), but it is actually equal to 0.1000000000000000055511151231257827021181583404541015625. This is because 0.1 cannot be represented exactly as a double (or, for that matter, as a binary fraction of any finite length). Thus, the value that is being passed in to the constructor is not exactly equal to 0.1, appearances notwithstanding.

The solution is to use the BigDecimal(String) constructor instead:

public static void main(String[] args) {
    final BigDecimal b = new BigDecimal("123.1000");
    System.out.println(b.setScale(2, BigDecimal.ROUND_DOWN));
}

Which works exactly as you would expect.

123.10

Process finished with exit code 0
JonK
  • 2,097
  • 2
  • 25
  • 36