2

I have two @Entitys, both with a BigDecimal field as follows:

in one module:

@Entity
@Table(name = "price_range")
public class PriceRange extends AbstractPersistable<Long> {
    @Column(name = "price", precision = 19, scale = 4)
    private BigDecimal price;

and in another module:

@Entity
@Table(name = "invoice_position")
public class InvoicePosition extends AbstractPersistable<Long> {
    @Column(name = "optimized_cost", precision = 19, scale = 4)
    private BigDecimal optimizedCost;

both create tables in my database with the correct precision and scale values:

Table invoice_position
======================
id,optimized_cost, ...
----------------------
optimized_cost   decimal(19,4)

and

Table price_range
=================
id, price, ...
-----------------
price            decimal(19,4)

A Test Frontend saves the values correctly to the database.

However in a unit test, one of the two returns a value with a rounding error:

0.520000000000000017763568394002504646778106689453125

(debugger says: sacle = 51 and precision = 0)

while the other is working fine:

0.5200

(debugger says: scale = 4, precision = 4)

Both values are retrieved from the database in the same way (with an EntityManager building a CriteriaQuery with a CriteriaBuilder inside a JpaRepository):

List<Invoice> invoices = invoiceProvider.findAll();
List<PriceRange> priceRanges = priceRangeProvider.findAll();

What could be the problem here? Or better: Where could it go wrong, if the Entity has the correct scale and precision and the database as well?

I'm quite at a loss here, where can I look for the error?

Pete
  • 10,720
  • 25
  • 94
  • 139
  • 1
    See http://stackoverflow.com/questions/5734036/hibernate-loss-of-precision-in-results-when-mapping-a-number-22-21-to-bigdecim – axtavt Jan 24 '12 at 15:26
  • Looks like that could be it. What's the best practice then for initializing `BigDecimal` in a unit test? Using `String` feels... weird.. – Pete Jan 24 '12 at 15:28
  • You can also initialize them with `long` and scale, but it doesn't look good too. – axtavt Jan 24 '12 at 15:31
  • 1
    Still, using a String is the correct way to go. Anything else will fail because of rounding error. – parasietje Jan 24 '12 at 16:02

1 Answers1

1

Alright, marking this as answered as per comments with the solution being this

Community
  • 1
  • 1
Pete
  • 10,720
  • 25
  • 94
  • 139