Search code examples
javajava-money

Convert MonetaryAmount to long of minor units (Javamoney)


Using the JSR-354 Java Money API (Moneta in this case), I can easily create a MonetaryAmount object from a long of minor units (pence in this case):

MonetaryAmount amount = Money.ofMinor(Monetary.getCurrency("GBP"), 1234); //£12.34

...but how do I query this MonetaryAmount back for its minor units in the same way? I can do:

amount.getNumber().longValue();

...but that only gives the major units, truncating the minor units entirely.


Solution

  • long minorUnits = monetaryAmount.query(MonetaryQueries.convertMinorPart()); //1234
    

    Other values on MonetaryQueries can also be used to extract just the minor part if required (which would return 34 in the above case.)