jsr354-ri
jsr354-ri copied to clipboard
Money.of with scaled BigDecimal leads to unexpected getNumber value
When a MonetaryAmount is instantiated with a scaled BigDecimal, then extracting the big decimal using Money#getNumber leads to a BigDecimal with unexpected scale (e.g. "-1").
Example
@Test
void whenMonetaReceivesBigDecimal_thenItHandlesItAccordingly(){
BigDecimal amount = BigDecimal.valueOf(1000,2);
Money money = Money.of(amount, "EUR");
assertEquals("EUR 10.00", money.toString());
assertEquals(amount, money.getNumber().numberValueExact(BigDecimal.class));
}
... leads to the following test-failure ...
java.lang.AssertionError:
Expected :1E+1
Actual :10.00
Background
Using Hibernate with the Jadira multi column user type (or any other Hibernate user type I guess) leads to creation of BigDecimal with a given scale. When on the other end the service returns e.g. BigDecimal - this leads to false service responses.
Workaround
Creating a new BigDecimal with the currencies scale solves the issue.
assertEquals(
amount,
money.getNumber().numberValueExact(BigDecimal.class)
.setScale(money.getCurrency().getDefaultFractionDigits())
);