print jodamoney without decimals

467 Views Asked by At

I know how to print a joda-money object using the MoneyFormatterBuilder:

Money m = Money.of(CurrencyUnit.USD, 48209);
System.out.println(new MoneyFormatterBuilder().appendAmount(MoneyAmountStyle.ASCII_DECIMAL_POINT_GROUP3_COMMA).toFormatter().print(m));

But this prints it with decimals:

48,209.00

How do I print a joda-money object with no decimals? And have it round up if necessary? So that the output of the above would be:

48,209

And (another example) 48209.69 would print 48210?

2

There are 2 best solutions below

1
On

You can rounding money and then get string value out of it and replace decimal places.

@Test
void formatMoney() {
    Arrays.asList(10.44d, 10.45d, 10.46d, 10.50d, 10.55d).forEach(
            d -> {

                Money money = Money.of(CurrencyUnit.USD, d);

                LOGGER.info("Money with decimal: {}\tRounded money: {}\tFormatted string out of money: {}",
                    money,
                    money.rounded(0, RoundingMode.HALF_UP),                
                    money.rounded(0, RoundingMode.HALF_UP).toString().replace(".00","")); 
            }
    );
}
0
On

You can use BigMoney.

Try with this:

BigDecimal bigDecimal = new BigDecimal("48209.60");
BigMoney m = BigMoney.of(CurrencyUnit.USD, bigDecimal.setScale(0,RoundingMode.HALF_UP));
System.out.println(new MoneyFormatterBuilder().appendAmount(MoneyAmountStyle.ASCII_DECIMAL_POINT_GROUP3_COMMA).toFormatter().print(m));