How to Format Number as Currency String in Java

How to Format Number as Currency String in Java

Introduction

Currency is a very important part of our modern world. So, it's equally important for us to be able to properly express it in Java.

In this tutorial, we'll go over how to format numbers as currency Strings in Java.

Format Number as Currency String

Here's how you can easily format a number, such as a double into a currency String:

double currencyAmount = 1500.00;
// Create a new Locale
Locale usa = new Locale("en", "US");
// Create a Currency instance for the Locale
Currency dollars = Currency.getInstance(usa);
// Create a formatter given the Locale
NumberFormat dollarFormat = NumberFormat.getCurrencyInstance(usa);

// Format the Number into a Currency String
System.out.println(dollars.getDisplayName() + ": " + dollarFormat.format(currencyAmount));

If we run this code, it'll result in:

US Dollar: $1,500.00

Formatting numbers in different currencies involves a few Java classes. Our example made use of the Locale and Currency classes from the java.util package. Additionally, we used the NumberFormat class, which can be found in the java.text package.

Let's dive deeper into these classes and write a method that formats our number into multiple currencies, depending on an input.

The Locale Class

Each Locale object expresses a geopolitical region and includes information such as language and location. Countries have unique ways of expressing currency. Instead of us having to manually format each currency differently, using Locale objects allow us to automate this process.

To create a new Locale object, we can use one of the three available constructors:

Locale(String language);
Locale(String language, String country);
Locale(String language, String country, String variant);

Do note, however, that the String parameters for the constructors cannot be arbitrary. You can find a full list of all supported locales in Java 8 here.

Now let's create some example Locale objects. We will reference these later when we are creating the actual method for printing out currency:

Locale usa = new Locale("en", "US");
Locale germany = new Locale("de", "DE");
Locale japan = new Locale("jp", "JP");

Since we are working with currency, the first String parameter, language, will dictate the formatting of the currency value (ex. 1,000,000.00 or 1.000.000,00). The second String parameter, region, will determine which currency sign is used (ex. $ or ¥).

The Currency Class

The second class that we need to understand is the Currency class. Each Currency object represents a world currency. We want to get a currency given our Locale, so we will be using the following method:

Currency.getInstance(Locale locale);

This will return the corresponding Currency instance for the specified Locale parameter. So, using the Locale objects we created previously, this is what we will do:

Currency dollars = Currency.getInstance(usa);
Currency euros = Currency.getInstance(germany);
Currency yen = Currency.getInstance(japan);

Now that we have created our three Currency instances, we can move on to our next class.

The NumberFormat Class

The NumberFormat class has methods to format numbers based on locales. Countries have different ways of grouping numbers. For example, one thousand can be represented as "1000", "1,000", "1 000" and other variations.

We'll be using the NumberFormat.getCurrencyInstance(Locale l) method. This method returns a NumberFormat object that corresponds to the Locale parameter specified. This is how we'll be using it in our method:

NumberFormat dollarFormat = NumberFormat.getCurrencyInstance(usa);
NumberFormat eurosFormat = NumberFormat.getCurrencyInstance(germany);
NumberFormat yenFormat = NumberFormat.getCurrencyInstance(japan);

Creating a Method to Print a Number as a Currency

Now that we have learned about the three classes needed for this program, we can start writing the actual method to print a double with currency formatting.

We'll also accept a String, specifying which currency we'd like to print it as:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

public static void printCurrency(double currencyAmount, String outputCurrency) {
    Locale locale;
		
    if (outputCurrency.equals("Yen")) {
	    locale = new Locale("jp", "JP");
	} else if(outputCurrency.equals("Euros")) {
        locale = new Locale("de", "DE");
	} else if (outputCurrency.equals("Dollars")) {
        locale = new Locale("en", "US");
    } else {
        locale = new Locale("en", "US");
    }
	    
	Currency currency = Currency.getInstance(locale);
	NumberFormat numberFormat = NumberFormat.getCurrencyInstance(locale);
	
	System.out.println(currency.getDisplayName() + ": " + numberFormat.format(currencyAmount)); 

	}
}

Let's test this method out by calling it and passing in the appropriate arguments:

printCurrency(1000000.00, "Yen");
printCurrency(1000000.00, "Dollars");
printCurrency(1000000.00, "Euros");

This results in:

Japanese Yen: JPY 1,000,000
US Dollar: $1,000,000.00
Euro: 1.000.000,00 €

For this example, we used a double and printed as currency with proper formatting. Other number types would work as well, but we advise to stick with double for currency values.

Conclusion

In this article, we learned a bit about the Locale, Currency, and NumberFormat classes. We then applied this knowledge in a method that allowed us to correctly format and print a double as currency.

Last Updated: January 20th, 2021
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Want a remote job?

    Prepping for an interview?

    • Improve your skills by solving one coding problem every day
    • Get the solutions the next morning via email
    • Practice on actual problems asked by top companies, like:
     
     
     

    Better understand your data with visualizations

    With over 330+ pages, you'll learn the ins and outs of visualizing data in Python with popular libraries like Matplotlib, Seaborn, Bokeh, and more.

    © 2013-2021 Stack Abuse. All rights reserved.