拿这个 SSCCE(安装了 Joda-Money 库):
public static void main(String[] args) {
BigDecimal bd = new BigDecimal("100");
MoneyFormatter mf = new MoneyFormatterBuilder().appendLiteral("$ ").appendAmount(MoneyAmountStyle.LOCALIZED_GROUPING).toFormatter();
String money_as_string = mf.print(Money.of(CurrencyUnit.USD, bd)); // The MoneyFormatter is what printed this string...
System.out.println(money_as_string);
Money money = mf.parseMoney(money_as_string); // You think it should be able to parse the string it gave me, right?
}
我用MoneyFormatter
来打印String
: money_as_string
。我的(合理的?)期望是我可以使用相同MoneyFormatter
的方法将字符串解析回Money
对象。但是,唉,没有骰子。它抛出这个错误:
Exception in thread "main" org.joda.money.format.MoneyFormatException: Parsing did not find both currency and amount: $ 100.00
at org.joda.money.format.MoneyFormatter.parseBigMoney(MoneyFormatter.java:237)
at org.joda.money.format.MoneyFormatter.parseMoney(MoneyFormatter.java:258)
at test4.Test12.main(Test12.java:35)
所以,我的问题是:一个人究竟是如何Money
从 a 中得到一个对象的String
?
编辑:@durron597,您的信息很有帮助,但没有回答问题。那么,你究竟是如何从一个对象转到String
一个Money
对象的呢?
我添加了删除美元符号的代码:
public static void main(String[] args) {
BigDecimal bd = new BigDecimal("100");
MoneyFormatter mf = new MoneyFormatterBuilder().appendLiteral("$ ").appendAmount(MoneyAmountStyle.LOCALIZED_GROUPING).toFormatter();
String money_as_string = mf.print(Money.of(CurrencyUnit.USD, bd)); // The MoneyFormatter is what printed this string...
System.out.println(money_as_string);
Money money = mf.parseMoney(money_as_string.replace("$", "").trim()); // You think it should be able to parse the string it gave me, right?
}
我得到了这个:
Exception in thread "main" org.joda.money.format.MoneyFormatException: Text could not be parsed at index 0: 100.00
at org.joda.money.format.MoneyFormatter.parseBigMoney(MoneyFormatter.java:233)
at org.joda.money.format.MoneyFormatter.parseMoney(MoneyFormatter.java:258)
at test4.Test12.main(Test12.java:35)
因此,它无法解析带有或不带有货币符号的文本。
任何人都可以使该parseMoney()
功能正常工作吗?