Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Money.of with scaled BigDecimal leads to unexpected getNumber value #375

Closed
l-ray opened this issue Jan 24, 2022 · 1 comment
Closed

Money.of with scaled BigDecimal leads to unexpected getNumber value #375

l-ray opened this issue Jan 24, 2022 · 1 comment
Labels
analysis external External parties or libraries involved

Comments

@l-ray
Copy link

l-ray commented Jan 24, 2022

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())
);
@keilw keilw added external External parties or libraries involved analysis labels Jun 5, 2022
@keilw
Copy link
Member

keilw commented Feb 15, 2023

Not sure, which version of Moneta you used for this, but after #357 has been addressed, the assertion would fail:

     BigDecimal amount = BigDecimal.valueOf(1000,2);
     Money money = Money.of(amount , "EUR");
     assertEquals(money.toString(), "EUR 10.00");

java.lang.AssertionError:
Expected :EUR 10.00
Actual   :EUR 10

And you may tweak your Money

     BigDecimal amount = BigDecimal.valueOf(1000,2);
     Money money = Money.of(amount , "EUR", MonetaryContextBuilder.of().setMaxScale(2).setFixedScale(true).build());
     assertEquals(money.toString(), "EUR 10.00");

To set the desired scale, otherwise it takes the scale of the BigDecimal which was 0 in the initial example.

@keilw keilw closed this as completed Feb 15, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
analysis external External parties or libraries involved
Projects
None yet
Development

No branches or pull requests

2 participants