Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I override Currency symbols in Java?

I'm trying to print prices in Turkish Liras (ISO 4217 currency code TRY) with Java.

When I do

Currency curr = Currency.getInstance("TRY");
Locale trLocale = new Locale("tr", "TR");
System.out.println(curr.getSymbol(trLocale));

the output is: "YTL".

However, the currency symbol for Turkish Lira has recently changed from "YTL" to "TL" (as can be seen on the Wikipedia page for Turkish Lira). Formatting with NumberFormat gives a similar result.

I really don't want to write yet another Currency class, especially when Java has one built-in.

Is there a way to override Java's default currency symbol for TRY to "TL"?

like image 423
user110665 Avatar asked May 21 '09 17:05

user110665


2 Answers

Resurrection for further reference:

You can use DecimalFormatSymbols to change the Currency for Formatting purposes

Locale trLocale = new Locale("tr", "TR");
DecimalFormat decimalFormat = (DecimalFormat) DecimalFormat.getCurrencyInstance(trLocale);
DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(trLocale);
dfs.setCurrencySymbol("TL");
decimalFormat.setDecimalFormatSymbols(dfs);

Or you can appeal to SPI and plug-in your currency symbol (maybe by creating your own country variant like new Locale("tr","TR","try")). In order to do that you should provide a implementation to java.util.spi.CurrencyNameProvider and register it with Java extension mechanism. Check out http://java.sun.com/javase/6/docs/api/java/util/spi/LocaleServiceProvider.html

like image 92
Anthony Accioly Avatar answered Oct 22 '22 05:10

Anthony Accioly


Amusingly, according to Wikipedia, the currency code "TRL" is obsolete (the old code for Turkish lira). I have not upgraded to the latest jdk, (on 1.5.0_10), but

Currency curr = Currency.getInstance("TRL");
Locale trLocale = new Locale("tr", "TR");
System.out.println(curr.getSymbol(trLocale));

Prints:

TL

So perhaps write something of your own to map existing codes to obsolete codes and adjust and test as needed.

like image 3
benson Avatar answered Oct 22 '22 05:10

benson