Take this SSCCE (with Joda-Money library installed):
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?
}
I used the MoneyFormatter
to print the String
: money_as_string
. My (reasonable?) expectation was that I could use the same MoneyFormatter
to parse the string back into a Money
object. But, alas, no dice. It throws this error:
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)
So, my question is: how exactly does one get a Money
object from a String
?
EDIT: @durron597, your information was helpful but did not answer the question. How, exactly, do you go from a String
to a Money
object then?
I added code to remove the dollar sign:
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?
}
and I got this:
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)
So, it can't parse the text with or without the currency symbol.
Can anyone get the parseMoney()
function to work, ever??
So the first thing that stood out to me is that you were using
appendLiteral
and notappendCurrencySymbolLocalized
(what if you were usingCurrencyUnit.EUR
? You wouldn't want a $).However, when you change it to this:
Your code instead throws this exception:
Further examination reveals this telling line in the javadoc:
Why might that be? Probably because currency symbols are ambiguous. Many countries use a dollar. Here are some examples:
Try this code:
This will make something like
USD 100.00
print, which will be parsed properly. If you absolutely must have the dollar symbol, you are going to need to implement your own printer/parser. Or you could use this one: