Search code examples
javaformatcurrency

Is there any library to format currency values in java?


I have currency code and value in double. Need to do formating for Currencies.I tried with NumberFormat and Locale but in this case for example EURO has different Locale related to countries. How can I achieve this?, Is there any common format for Euro?

       format.setCurrency(Currency.getInstance("EUR"));
       format.setMaximumFractionDigits(2);
       
       System.out.println(format.format(dbl));

Locale[] locales = NumberFormat.getAvailableLocales();

       for(Locale lo : locales){
           NumberFormat format = NumberFormat.getCurrencyInstance(lo);
           if(NumberFormat.getCurrencyInstance(lo).getCurrency().getCurrencyCode().equals("EUR")){
          
               System.out.println(    NumberFormat.getCurrencyInstance(lo).getCurrency().getCurrencyCode()+"-"+lo.getDisplayCountry() +"-"+NumberFormat.getCurrencyInstance(lo).getCurrency().getSymbol() +format.format(dbl));  

           }
       }```

Solution

  • I have been using icu4j library from a long time and it serves this purpose very well. It has many number formatters, including currency formatter. Please check below code:

    final com.ibm.icu.text.NumberFormat rule = RuleBasedNumberFormat.getCurrencyInstance(new Locale("en", "EU"));
    System.out.println(rule.format(1054979.30));
    

    It will print: €1,054,979.30

    There are many configurations which will help you to tweak the output.

    EDIT:

    If you want to pass the currency code and format according to that, below is the code for it:

    final com.ibm.icu.text.NumberFormat rule = RuleBasedNumberFormat.getCurrencyInstance();
    rule.setCurrency(Currency.getInstance("EUR"));
    System.out.println(rule.format(1054979.30));