Is there a way to construct a MonetaryAmount from a whole cents value?

986 Views Asked by At

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);
2

There are 2 best solutions below

0
On BEST ANSWER

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

2
On

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   
*/