jan
jan

Reputation: 4051

Storing currency as BigDecimal in Hibernate/JPA - decimal(19,2)

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?

Upvotes: 1

Views: 2767

Answers (1)

Sudhir Dhumal
Sudhir Dhumal

Reputation: 970

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

Upvotes: 1

Related Questions