Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing Bitcoin and java.util.Currency

I'm trying to add bitcoin as a currency to display on my site. I've got exchange rates and everything, but I keep getting an IllegalArgumentException whenever I use java.util.Currency.getInstance("BTC"). This makes sense since it's not included in the list of ISO 4217 currency codes, and also not in Java 7. I've seen a couple of options, but nothing that really solves my issue.

  1. According to the Java platform docs, you can override a specific locale's currency by creating a file $JAVA_HOME/lib/currency.properties. This is a problem since bitcoin is not tied to a specific locale, nor should it be used in place of any country's currency.

  2. Another similar situation was presented in this StackOverflow post, where China had a second currency code to be used, so the solution was to build your own currency.data file that added a second currency for the China locale. This is better, but there is still the issue of tying a currency to a locale.

Has anyone run into this problem or found a workaround? I know bitcoin is relatively new, but it'd be cool to be able to display prices in bitcoin format.

like image 944
tedski Avatar asked Dec 09 '13 15:12

tedski


1 Answers

You cannot use BTC as the currency code for bitcoins under ISO 4217. BT is reserved for Bhutan. However, ISO 3166-1 reserves several country codes for user definition. Additionally, the wiki for ISO 4217 lists XBT as a currency code for bitcoins (unofficially, of course).

Locale.Builder b = new Locale.Builder();
b.setRegion("XB");
Locale xb = b.build();
Currency bitcoin = Currency.getInstance(xb);

Your currency.properties file will look like:

XB=XBT,000,3

Unfortunately, you cannot have 8 for the minor unit because the parsing for java.util.Currency only handles a minor unit of 0-3:

Pattern propertiesPattern = Pattern.compile("([A-Z]{3})\\s*,\\s*(\\d{3})\\s*,\\s*([0-3])");
like image 64
Jeffrey Avatar answered Sep 29 '22 15:09

Jeffrey