JavaMoney / jsr354-ri

JSR 354 - Moneta: Reference Implementation
Other
344 stars 101 forks source link

How do I parse "$1000.00" in current versions? #423

Open lvh opened 1 week ago

lvh commented 1 week ago

I'm trying to parse some USD amounts formatted like "$1000" or "$1000.00". I know, from context, they're USD--I understand $ is used for other currencies too. I upgraded from moneta 1.1 to .1.4.4, which broke this previously working code. (The code is in Clojure but the meaning is presumably obvious if you're familiar with the Java equivalent.)

(def us-format
  (->
   (AmountFormatQueryBuilder/of Locale/US)
   (.set CurrencyStyle/SYMBOL)
   (.build)
   (MonetaryFormats/getAmountFormat)))

Parsing a string like $1000.00 results in the following error:

Unhandled javax.money.format.MonetaryParseException
   $ is not a unique currency symbol.

Googling the error points to https://github.com/JavaMoney/jsr354-ri/issues/274, but that appears to mostly be the ticket that introduced the issue. That ticket seems to suggest there's no solution, but I don't know if it's simply outdated.

I submit that in the context of a US Locale, "$1000.00" is relatively unambiguous: it clearly means USD (the same way that in Canada a reasonable person would expect it to mean CAD). But, I'm fine with explicitly specifying the currency since I know what it is:

(def usd
  (Monetary/getCurrency "USD" (into-array String [])))

(def us-format
  (->
   (AmountFormatQueryBuilder/of Locale/US)
   (.set CurrencyStyle/SYMBOL)
   (.set CurrencyUnit usd) ;; <= new line
   (.build)
   (MonetaryFormats/getAmountFormat)))

However, this also doesn't work, with the same error. I submit that "the currency code is unambiguous" is irrelevant: I already specified what the currency is unambiguously. When I call .format on that AmountFormat it seems more than happy to give me $ back.

How do I parse $1000.00 in Moneta?