I'm really confused about how to customize a MonetaryAmountFormat
using the Moneta JSR-354 implementation.
My intention is to be able to parse both 1.23
and $3.45
as MonetaryAmount
s.
Here is my unit test:
@Test
public void testString() {
Bid bid = new Bid("1.23");
assertEquals(1.23, bid.getValue(), 0.0);
System.out.println(bid);
bid = new Bid("$3.45");
assertEquals(3.45, bid.getValue(), 0.0);
System.out.println(bid);
}
Here is my class:
public final class Bid {
private static final CurrencyUnit USD = Monetary.getCurrency("USD");
private MonetaryAmount bid;
/**
* Constructor.
*
* @param bidStr the bid
*/
public Bid(String bidStr) {
MonetaryAmountFormat format = MonetaryFormats.getAmountFormat(
AmountFormatQueryBuilder.of(Locale.US)
.set("pattern", "###.##")
.build());
if (StringUtils.isNotBlank(bidStr)) {
bidStr = bidStr.trim();
bidStr = bidStr.startsWith("$") ? bidStr.substring(1) : bidStr;
try {
bid = FastMoney.parse(bidStr, format);
} catch (NumberFormatException e) {
bid = FastMoney.of(0, USD);
}
}
}
/**
* Constructor.
*
* @param bidDouble the bid
*/
public Bid(double bidDouble) {
bid = FastMoney.of(bidDouble, USD);
}
public double getValue() {
return bid.getNumber().doubleValue();
}
}
I would have really liked to be able to parse the bidStr
with or without the $
using the single MonetaryAmountFormat
, but after spending a lot of time trying to find out how to make $
optional, I gave up. Unfortunately, I can't even figure out how to make 1.23
get parsed as USD. Moneta throws a NullPointerException
. Am I supposed to set a currency using the AmountFormatQueryBuilder
? What are all the keys that can be set using the AmountFormatQueryBuilder
? I searched for documentation, but couldn't find any anywhere, except for a couple of common keys, like pattern
.