Reputation: 23
I'm trying to create a MonetaryAmountFormat
that uses the currency unit symbol:
MonetaryAmountFormat format = MonetaryFormats.getAmountFormat(
AmountFormatQueryBuilder.of(Locale.GERMANY)
.set(org.javamoney.moneta.format.CurrencyStyle.SYMBOL)
.set("pattern", "#,##0.##¤")
.build()
);
(Taken from How to format MonetaryAmount with currency symbol? and Customizing a MonetaryAmountFormat using the Moneta (JavaMoney) JSR354 implemenation).
The java/maven project has a dependency on moneta in runtime (not compile-time) scope. It seems that the class CurrencyStyle
and its value SYMBOL
are part of moneta, the java-money reference implementation, and not part of the java-money API. Thus, the code does not compile.
I created this ugly workaround:
String currencyStyle = "org.javamoney.moneta.format.CurrencyStyle";
final Enum<?> SYMBOL = Enum.valueOf((Class<? extends Enum>) Class.forName(currencyStyle), "SYMBOL");
MonetaryAmountFormat format = MonetaryFormats.getAmountFormat(
AmountFormatQueryBuilder.of(Locale.GERMANY)
.set(currencyStyle, SYMBOL)
.set("pattern", "#,##0.##¤")
.build()
);
Is it possible to create a MonetaryAmountFormat
that uses the currency unit symbol without this hack?
Upvotes: 1
Views: 508
Reputation: 146
Maybe using DecimalFormat
as alternative to MonetaryAmountFormat
is an option.
Drawbacks:
Number
and MonetaryAmount
must be done manuallyMonetaryAmount
object)Example:
NumberFormat format = new DecimalFormat("#,##0.##¤", DecimalFormatSymbols.getInstance(Locale.GERMANY));
// format
MonetaryAmount source = ...;
String formattedAmount = format.format(source.getNumber());
// parse
Number numberAmount = format.parse(formattedAmount);
MonetaryAmount target = Monetary.getDefaultAmountFactory().setCurrency("EUR").setNumber(numberAmount).create()
Upvotes: 0