4

Given a price-point represented as an integer of whole cents, i.e. 199 = $1.99, is there an API method for constructing a MonetaryAmount?

One simple method would be to divide the amount by 100, but wondering if there's an API method for this.

MonetaryAmount ma = Money.of(199, "NZD").divide(100);
Brett Ryan
  • 26,937
  • 30
  • 128
  • 163
  • All I could find is [Money.of(199, "NZD").scaleByPowerOfTen(-2)](http://mavenbrowse.pauldoo.com/central/javax/money/money-api/0.8/money-api-0.8-javadoc.jar/-/javax/money/MonetaryAmount.html#scaleByPowerOfTen(int)) ... – A4L Aug 07 '15 at 07:23
  • I thought about that also but was concerned about the scale being changed with it. From what I'd imagine the original dollar value would ultimately be the same since the scale changes with the value. Haven't tested the theory. – Brett Ryan Aug 07 '15 at 07:26

2 Answers2

8

The Money.ofMinor() method is exactly what you are looking for.

Obtains an instance of Money from an amount in minor units.
For example, ofMinor(USD, 1234, 2) creates the instance USD 12.34

Sergey Ponomarev
  • 2,947
  • 1
  • 33
  • 43
-1

I'm not sure if this is useful to you. It works, though.

private void convert() {
    DecimalFormat dOffset = new DecimalFormat();
    DecimalFormat dFormat = new DecimalFormat("#,##0.00");        
    dOffset.setMultiplier(100);


    String value2, value1;

    String str;
    try {
        value1 = "0";
        value2 = dFormat.format(dOffset.parse(value1));
        System.out.println(value2);

        value1 = "7";
        value2 = dFormat.format(dOffset.parse(value1));
        System.out.println(value2);

        value1 = "04";
        value2 = dFormat.format(dOffset.parse(value1));
        System.out.println(value2);

        value1 = "123";
        value2 = dFormat.format(dOffset.parse(value1));
        System.out.println(value2);

        value1 = "123456";
        value2 = dFormat.format(dOffset.parse(value1));
        System.out.println(value2);


    } catch (ParseException ex) {
        ex.printStackTrace();
    }        
}

/* Output
    0.00
    0.07
    0.04
    1.23
    1,234.56   
*/
d_air
  • 631
  • 1
  • 4
  • 12
  • 1
    I'm after a [jsr-354](https://www.jcp.org/en/jsr/detail?id=354) specific answer for creating instances of `MonetaryAmount`. What I'd like to see is something like `Money.of(199, "NZC")`. – Brett Ryan Aug 07 '15 at 06:36
  • 1
    Money.ofMinor(NZC, 199) is what you are looking for – Sergey Ponomarev Aug 31 '16 at 20:16