Java JSR-354 MonetaryMountFormat对于美元、和#x20AC以外的其他货币符号不起双向作用;或£;
下面是我正在使用的示例代码: 这应该是可行的,因为我正在来回转换相同的对象。除非我弄错了什么,而且对于美元、欧元或英镑以外的其他货币,转换器不是双向的 最后一行与以下内容崩溃:Java JSR-354 MonetaryMountFormat对于美元、和#x20AC以外的其他货币符号不起双向作用;或£;,java,internationalization,currency-formatting,java-money,jsr354,Java,Internationalization,Currency Formatting,Java Money,Jsr354,下面是我正在使用的示例代码: 这应该是可行的,因为我正在来回转换相同的对象。除非我弄错了什么,而且对于美元、欧元或英镑以外的其他货币,转换器不是双向的 最后一行与以下内容崩溃: Exception in thread "main" java.lang.IllegalArgumentException: Invalid error index > input.length at javax.money.format.MonetaryParseException.<init>(Mo
Exception in thread "main" java.lang.IllegalArgumentException: Invalid error index > input.length
at javax.money.format.MonetaryParseException.<init>(MonetaryParseException.java:56)
at org.javamoney.moneta.internal.format.AmountNumberToken.parse(AmountNumberToken.java:140)
at org.javamoney.moneta.internal.format.DefaultMonetaryAmountFormat.parse(DefaultMonetaryAmountFormat.java:190)
at test.main(test.java:27)
有没有办法让我上面的代码适用于美元、欧元或英镑以外的货币
我尝试了更多的东西,例如提供的Locale.CANADA,它们还有$作为货币符号,所以它执行时不会失败,但返回错误的数据
Locale LANG = Locale.CANADA;
final MonetaryAmountFormat format = MonetaryFormats.getAmountFormat(
AmountFormatQueryBuilder.of(LANG)
.set(CurrencyStyle.SYMBOL)
.set("pattern", "#,##0.00### ¤")
.build()
);
final String formatted = format.format(Money.of(new BigDecimal("1234.56"), Monetary.getCurrency(LANG)));
System.out.println(formatted);
System.out.println(format.parse(formatted).getCurrency().getCurrencyCode());
最后一行返回
USD
,而不是CAD
,这就是if else对美元的作用。我认为它还错误地假设符号-货币是一对一的映射。我们正在研究一个解决方案,提出了一些问题
预计Moneta将很快为该问题和其他问题提供补丁
沃纳
case SYMBOL:
if (token.startsWith("$")) {
cur = Monetary.getCurrency("USD");
context.consume("$");
} else if (token.startsWith("€")) {
cur = Monetary.getCurrency("EUR");
context.consume("€");
} else if (token.startsWith("£")) {
cur = Monetary.getCurrency("GBP");
context.consume("£");
} else {
cur = Monetary.getCurrency(token);
context.consume(token);
}
context.setParsedCurrency(cur);
break;
Locale LANG = Locale.CANADA;
final MonetaryAmountFormat format = MonetaryFormats.getAmountFormat(
AmountFormatQueryBuilder.of(LANG)
.set(CurrencyStyle.SYMBOL)
.set("pattern", "#,##0.00### ¤")
.build()
);
final String formatted = format.format(Money.of(new BigDecimal("1234.56"), Monetary.getCurrency(LANG)));
System.out.println(formatted);
System.out.println(format.parse(formatted).getCurrency().getCurrencyCode());