How to format a number as currency depending on Locale in Java

Overview

Every country has its own unique way of expressing currency. Hence, expressing the currency in a proper format becomes crucial when dealing with currencies. Manually formatting currency for every country is a tedious process.

Java provides an automated way for formatting currencies depending on the locale.

getCurrencyInstance() is a static method of the NumberFormat class that returns the currency format for the specified locale.

Note: A Locale in Java represents a specific geographical, political, or cultural region.

Syntax

public static NumberFormat getCurrencyInstance(Locale inLocale)

Parameters

  • Locale inLocale: The desired locale.

Return value

The method returns a NumberFormat instance for the given locale.

Code

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.Locale;
public class Main {
public static void main(String[] args){
BigDecimal valueToFormat = new BigDecimal("432.6542");
NumberFormat franceFormat = NumberFormat.getCurrencyInstance(Locale.FRANCE);
String formattedString = franceFormat.format(valueToFormat);
System.out.println(formattedString);
}
}

Explanation

  • Lines 1 to 3: We import the relevant packages.
  • Line 8: We define a BigDecimal value to format called valueToFormat.
  • Line 9: We get the currency format for France using the getCurrencyInstance() method. The FRANCE locale is passed as an argument to the method. We name the obtained format as franceFormat.
  • Line 10: We get the formatted currency string using the format() method on franceFormat. valueToFormat is passed as an argument to the method.
  • Line 11: We print the formatted currency string.