Java: Currency symbol based on ISO 4217 currency cod

后端 未结 4 448
生来不讨喜
生来不讨喜 2021-02-05 06:45

Below program prints the Currency symbol given the ISO 4217 currency code.

import java.util.*;

public class Currency{

    public static void main(String args[]         


        
相关标签:
4条回答
  • 2021-02-05 07:07

    Currency.getSymbol() returns the currency symbol relative to the default locale.

    Gets the symbol of this currency for the default locale. For example, for the US Dollar, the symbol is "$" if the default locale is the US, while for other locales it may be "US$". If no symbol can be determined, the ISO 4217 currency code is returned.

    Use Currency.getSymbol(Locale locale) if you want the symbol for a different locale.

    System.out.println(
       Currency.getInstance("USD").getSymbol(Locale.US)
    );
    // prints $
    
    System.out.println(
       Currency.getInstance("USD").getSymbol(Locale.FRANCE)
    );
    // prints USD
    
    System.out.println(
       Currency.getInstance("EUR").getSymbol(Locale.US)
    );
    // prints EUR
    
    System.out.println(
       Currency.getInstance("EUR").getSymbol(Locale.FRANCE)
    );
    // prints €
    

    (see also on ideone.com).

    0 讨论(0)
  • 2021-02-05 07:12

    For me, your code even in the first case returns USD. It seemes, that Currency heavily depends on the JRE version (1.6 for me). Perosnally I recommend you to write your own CUR to symbol conversion module - it will be much easier, than try to use this one.

    0 讨论(0)
  • 2021-02-05 07:20

    Using the limited Locale enum's only caters for westernised symbols. If you want to be a little more global try using Locales provided by:

    Locale[] locales = Locale.getAvailableLocales();
    

    Using Locales from this list gave symbols rather than TLA's pretty consistently.

    0 讨论(0)
  • 2021-02-05 07:25

    If someone needs it the other way round (for example € -> EUR)

    String currency = €;
    String currencyCode = "";
    for (Currency c : Currency.getAvailableCurrencies()) {
        if (c.getSymbol().equals(currency)) {
            currencyCode = c.toString();
        }
    }
    
    0 讨论(0)
提交回复
热议问题