HowToDoInJava

  • Java 8
  • Regex
  • Concurrency
  • Best Practices
  • Spring Boot
  • JUnit5
  • Interview Questions
  • Dark Mode

Location Based Currency Formatting in Java

By Lokesh Gupta | Filed Under: Java Date/Time

Most of the applications today, which are targeted for a larger audience e.g. internet users, usually deal in money as well. In such application, a requirement will be to display money/currency in a format specific to that location or country. In this tutorial, I am giving some examples which will help you in location specific currency formatting in java.

I am first listing the classes used in examples, and then we will look at the real example codes.

Classes used in currency formatting in java

Below are the major java classes which are used to format locale based currencies.

  1. java.util.Locale : This class is used to get the location information of the end user which is currently using your application.
  2. java.util.Currency : This class represents a currency. The class is designed so that there’s never more than one Currency instance for any given currency. Therefore, there’s no public constructor. You obtain a Currency instance using the getInstance methods.
  3. java.text.NumberFormat : NumberFormat helps you to format and parse numbers for any locale. We will use it’s getCurrencyInstance() method to get the currency number formatter.

Read More: How to get current user locale

Currency formatting examples

Let’s list down very basic uses of above classes to display a raw number into currency format.

Format according to US locale

import java.text.NumberFormat;
import java.util.Currency;
import java.util.Locale;

public class NumberToCurrencyExamples
{
   public static void main(String[] args)
   {
      //This is the amount which we want to format
      Double currencyAmount = new Double(123456789.555);
      
      //Get current locale information
      Locale currentLocale = Locale.getDefault();
      
      //Get currency instance from locale; This will have all currency related information
      Currency currentCurrency = Currency.getInstance(currentLocale);
      
      //Currency Formatter specific to locale
      NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(currentLocale);

      //Test the output
      System.out.println(currentLocale.getDisplayName());
      
      System.out.println(currentCurrency.getDisplayName());
      
      System.out.println(currencyFormatter.format(currencyAmount));
   }
}

Output:

English (United States)
US Dollar
$123,456,789.56

Now let’s modify the locale to of France and observe the output:

Format according to FR locale

public static void main(String[] args)
{
  //This is the amount which we want to format
  Double currencyAmount = new Double(123456789.555);
  
  //Using France locale
  Locale currentLocale = Locale.FRANCE;
  
  //Get currency instance from locale; This will have all currency related information
  Currency currentCurrency = Currency.getInstance(currentLocale);
  
  //Currency Formatter specific to locale
  NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(currentLocale);

  //Test the output
  System.out.println(currentLocale.getDisplayName());
  
  System.out.println(currentCurrency.getDisplayName());
  
  System.out.println(currencyFormatter.format(currencyAmount));
}

Output:

French (France)
Euro
123 456 789,56 €

Easy enough. Isn’t it?

Please note that NumberFormat class OR Currency class does not convert the currencies using exchange rate logic. They are plain representation according to the location data provided by Locale class. If you want to convert between currencies then add some more logic in your application.

That’s all for this very basic usecase examples of currency formatting in java.

Happy Learning !!

Reference: http://docs.oracle.com/javase/tutorial/i18n/format/numberFormat.html

TwitterFacebookLinkedinRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

8
Leave a Reply

This comment form is under antispam protection
4 Comment threads
4 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
5 Comment authors
This comment form is under antispam protection
  Subscribe  
newest oldest most voted
Notify of
Sid

Hi Lokesh,

The Code which you provided is not working for Finland , India, Switzerland and lot many countries. Can i know is there any thing such that only some countries can will work

Vote Up0Vote Down  Reply
1 year ago
Lokesh Gupta

What format you are getting, and what you are expecting. Please share the code and output.

Vote Up0Vote Down  Reply
1 year ago
Augis

You should include https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency into account when working with currency.

Vote Up0Vote Down  Reply
4 years ago
Lokesh Gupta

In fact, I am more hopeful towards JSR 354: Money and Currency API. Anyways, thanks for the link, it was good read.

Vote Up0Vote Down  Reply
4 years ago
Keyur Bhatt

Hey, Thanks for such a good article. I am looking something like Custom Formatter available in .NET, like so exist in Java ? I am looking for totally custom formatter. If you know anything like this then please tell me.

Vote Up0Vote Down  Reply
4 years ago
Lokesh Gupta

I will look into it.

Vote Up0Vote Down  Reply
4 years ago
Libor Ondrušek

Hi.
I don’t know it is a good solution use currency in long life application. What if the currency of this state will change in future and you have no chance change the JDK of your application? (For example you app is deployed and customer can’t pay you for changes) Customers will expect actual currency and your application will depend on JDK version.

Vote Up0Vote Down  Reply
5 years ago
Lokesh Gupta

Thanks for sharing your thoughts. Further, I believe that no application is life long application, at least history teaches us so. An application without upgrade for so long time just seems too much hypothetical me. And changing the currency of any nation is also not frequent event. It happen perhaps once in one (or more) decade(s).

According to Java docs, Users can supersede the Java runtime currency data by creating a properties file named /lib/currency.properties. The contents of the properties file are key/value pairs of the ISO 3166 country codes and the ISO 4217 currency data respectively. The value part consists of three ISO 4217 values of a currency, i.e., an alphabetic code, a numeric code, and a minor unit. Those three ISO 4217 values are separated by commas.

Ref: https://docs.oracle.com/javase/7/docs/api/java/util/Currency.html

So, even if currency is changed to another currency then also we have some easy control to handle the scenario by changing a property file, which seems good enough for me.

Vote Up0Vote Down  Reply
5 years ago

Search Tutorials

Java Date Time Tutorial

  • Java 8 – LocalDate
  • Java 8 – LocalTime
  • Java 8 – LocalDateTime
  • Java 8 – ZonedDateTime
  • Java 8 – DateTimeFormatter
  • Java 8 – Get Current Date
  • Java 8 – Get Current Timestamp
  • Java 8 – Compare Dates
  • Java 8 – Convert to EST Timezone
  • Java 8 – Elapsed Time
  • Java 8 – Add days to Date
  • Java 8 – Duration between dates
  • Java 8 – Period between dates
  • Java – Date
  • Java – Locale
  • Java – Get Current Locale
  • Java – Check leap year
  • Java – Parse String to Date
  • Java – Format Calendar
  • Java – 12 hours pattern
  • Java – Currency Formatting
  • Java – Timezone Conversion
  • Java – Strict Date Validation
  • XMLGregorianCalendar to Date

Popular Tutorials

  • Java 8 Tutorial
  • Core Java Tutorial
  • Collections in Java
  • Java Concurrency
  • Spring Boot Tutorial
  • Spring AOP Tutorial
  • Spring MVC Tutorial
  • Spring Security Tutorial
  • Hibernate Tutorial
  • Jersey Tutorial
  • Maven Tutorial
  • Log4j Tutorial
  • Regex Tutorial

Meta Links

  • Advertise
  • Contact Us
  • Privacy policy
  • About Me

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2016 · HowToDoInjava.com · All Rights Reserved. | Sitemap

wpDiscuz