1

I changed the fields in my java application that hold currency values from double to BigDecimal to prevent strange double rounding issues like "0.20000000000001".

This now created the SQL date types of decimal(19,2), which means 2 digits right of the ".". Is this really a better way to store currency values or do I even lose precision this way?

jan
  • 3,923
  • 9
  • 38
  • 78

1 Answers1

1

If you don't want to loose precision value then you should use BigDecimal instead of BigInteger (in your Entity class in hibernate / JPA)

Consider following demo:

    // some calculation
    double calculatedValue = 0.20039930000;

    BigDecimal amount = new BigDecimal("" + calculatedValue).setScale(2,
            BigDecimal.ROUND_HALF_UP);
Sudhir Dhumal
  • 902
  • 11
  • 22
  • Sorry I meant BigDecimal, not BigInteger! Corrected my post – jan Jun 04 '14 at 17:18
  • Thanks for the answer! Can you explain some of its parts? Why doesn't `new BigDecimal(calculatedValue);` work? Why do you need to concatenate the double with a String? – Brad Turek Jun 28 '18 at 16:57
  • When I guess Josh built the API he built in such a way that, if we pass the value (not string) then it will do the calculation using primitive data type. In one of the Google IO event he explained and said its a bug in JDK and they have fixed it in their library(google's lib - at the time of IO event he was with google). And Sun/Oracle dont want to change the core API structure as it is used in multiple places and its been there since the introduction of BigDecimal class – Sudhir Dhumal Oct 20 '18 at 12:54