This took me a little while to work out. Moneta is the reference implementation of JSR 354 javax.money specification. It’s not particularly well documented.
Here’s how to parse monetary amounts that use a currency symbol like, for example $2.00 or £3.54 or €9.99.
The trick is to:
- set a pattern on your AmountFormatQueryBuilder
- use the currency sign, ¤, to represent the currency symbol in your pattern
- set the currency style to CurrencyStyle.SYMBOL
import static javax.money.format.MonetaryFormats.getAmountFormat;
import org.javamoney.moneta.format.CurrencyStyle;
import javax.money.format.MonetaryAmount;
import javax.money.format.MonetaryAmountFormat;
import java.util.Locale;
class MoneyTest {
private static final char CURRENCY_SIGN = '\u00A4';
public MonetaryAmoutn parse(String money) {
MonetaryAmountFormat maf = getAmountFormat(
AmountFormatQueryBuilder.of(Locale.UK)
.set("pattern", CURRENCY_SIGN + "0.00")
.set(CurrencyStyle.class, CurrencyStyle.SYMBOL)
.build()
);
return maf.parse(money);
}
}