0

I'm using BigDecimal data type, when I set

new BigDecimal(21.30);

then, I returned it as xml source, it shows as

21.30000000000710522735760100185871124467578125

Another number

new BigDecimal(23.11)

returned

23.1099999994315658113818187512921995859375

I want to show results with the same decimals as I set on create.

Vrian7
  • 588
  • 2
  • 6
  • 14

1 Answers1

7

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.

If you check the BigDecimal java doc you will find out that you will have to use the constructor which takes a String parameter to end up with the behavior you need.

Ioan M
  • 1,105
  • 6
  • 16
  • Simply adding `new BigDecimal("23.11")` would have been nice. Use backticks ` to quote code inside other text. Use indentation with 4 spaces for code blocks. – Joop Eggen May 22 '19 at 13:16
  • The above quoted text is taken from [the constructor documentation](https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/math/BigDecimal.html#%3Cinit%3E%28double%29). – VGR May 22 '19 at 14:21