Search code examples
javabigdecimal

Stange values after BigDecimal initialization


I'm trying to initialize a HashMap in the foolowing way:

HashMap<BigDecimal,BigDecimal> myMap = new HashMap<>();
myMap .put(new BigDecimal(1.7), new BigDecimal(1.5));
myMap .put(new BigDecimal(3.3), new BigDecimal(3));
myMap .put(new BigDecimal(5), new BigDecimal(4.5));
myMap .put(new BigDecimal(6.6), new BigDecimal(6));
myMap .put(new BigDecimal(11), new BigDecimal(10));
myMap .put(new BigDecimal(16.5), new BigDecimal(15));

but tha value above insert are change in the following wang:

1.7 becomes 1.6999999999999999555910790149937383830547332763671875
3.3 becomes 3.29999999999999982236431605997495353221893310546875
6.6 becomes 6.5999999999999996447286321199499070644378662109375

Why is happening this?


Solution

  • Use BigDecimal.valueOf(double) static method: this will initialize the BigDecimal from string representation of the double number which is what you need.