1. Introduction
Formatting numbers is essential in Java for clearly presenting data for reports, financial applications, or user interfaces. Java provides several classes for formatting numbers, including NumberFormat, DecimalFormat, and DecimalFormatSymbols. In this article, you will learn how to use these classes to format numbers, percentages, and currency values to fit the user’s location.
2. Creating a Number Formatter
The NumberFormat class allows you to format numbers according to different rules. You can create an instance using factory methods. You may provide the locale for which you want to format the number, but you can also use the default locale of your workstation.
The code below shows different ways of obtaining a NumberFormat object:
NumberFormat numberFormatter = NumberFormat.getNumberInstance();//Use the default locale
NumberFormat numberFormatterWithLocale = NumberFormat.getNumberInstance(Locale.FRANCE);
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance();
NumberFormat currencyFormatterWithLocale = NumberFormat.getCurrencyInstance(Locale.FRANCE);
NumberFormat percentageFormatter = NumberFormat.getPercentInstance();
NumberFormat percentageFormatterWithLocale = NumberFormat.getPercentInstance(Locale.FRANCE);
NumberFormat compactNumberFormatter = NumberFormat.getCompactNumberInstance();
NumberFormat compactNumberFormatterWithLocale = NumberFormat.getCompactNumberInstance(Locale.FRANCE,NumberFormat.Style.LONG);
3. Formatting Numbers
Once you have a NumberFormat object, you can use the format()
method to format the number according to the requirements.
3.1. Basic Formatting
The default NumberFormat class provides locale-sensitive number formatting:
NumberFormat numberFormatter = NumberFormat.getInstance(Locale.GERMANY);
double number = 1234567.89;
String formattedNumber = numberFormatter.format(number);
System.out.println(formattedNumber); // Output: 1.234.567,89
3.2. Currency Formatting
Java provides built-in support for formatting currency values using the NumberFormat
class. This ensures proper currency symbols and locale-based formatting.
Using NumberFormat for Currency Formatting
The NumberFormat.getCurrencyInstance()
method formats numbers as currency based on a specified locale.
double amount = 1234.56;
NumberFormat usFormatter = NumberFormat.getCurrencyInstance(Locale.US);
NumberFormat franceFormatter = NumberFormat.getCurrencyInstance(Locale.FRANCE);
String usFormattedNumber = usFormatter.format(amount);
String franceFormattedNumber = franceFormatter.format(amount);
System.out.println(usFormattedNumber); // Output: $1,234.56
System.out.println(franceFormattedNumber); // Output: 1 234,56 €
Customizing Currency Formatting
For more control, DecimalFormatSymbols can be used to customize currency symbols. However, you need to use the DecimalFormat constructor.
The DecimalFormat class provides three constructors:
- DecimalFormat(String pattern, DecimalFormatSymbols symbols): Accepts a string corresponding to the formatting pattern. The constructor also takes a DecimalFormatSymbols object to customize options like decimal separator, grouping separator, currency symbol, etc.
- DecimalFormat(String pattern): Same as the previous constructor, but uses the decimal symbols corresponding to the default locale.
- DecimalFormat(): The default constructor uses the pattern corresponding to the default locale and its decimal format symbols.
double amount = 1234.56;
DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.US);
symbols.setCurrencySymbol("USD$");
NumberFormat numberFormatter = new DecimalFormat("¤#,##0.00", symbols);
System.out.println(numberFormatter.format(amount)); // Output: USD$1,234.56
Here are important points about the formatting pattern:
- ‘#'(Hash sign) → Placeholder for an optional digit
- 0(Zero) → Placeholder for a mandatory digit
- ,(Comma) → Placeholder for Thousands separator(a.k.a. grouping separator)
- .(Dot) → Placeholder for Decimal separator
- ¤(Unicode U+00A4) → Placeholder for Currency symbol
3.3. Percentage Formatting
Java equally provides built-in support for formatting percentages using the NumberFormat
class. This ensures proper percentage representation based on locale and formatting rules.
Using NumberFormat for Percentage Formatting
The NumberFormat.getPercentInstance()
method formats decimal values as percentages.
NumberFormat percentFormatter = NumberFormat.getPercentInstance();
double value = 0.7563;
String percentFormatted = percentFormatter.format(value);
System.out.println(percentFormatted); // Output: 76%
Controlling Decimal Places in Percentage Formatting
By default, NumberFormat.getPercentInstance()
rounds percentages to whole numbers. To control decimal places, use setMinimumFractionDigits()
and setMaximumFractionDigits()
.
NumberFormat percentFormatter = NumberFormat.getPercentInstance();
percentFormatter.setMinimumFractionDigits(2);
double value = 0.7563;
String percentFormatted = percentFormatter.format(value);
System.out.println(percentFormatted); // Output: 75.63%
3.4. Compact Number Formatting
Java 12 introduced CompactNumberFormat to format large numbers in a readable way.
NumberFormat shortFormatter = NumberFormat.getCompactNumberInstance(Locale.US, NumberFormat.Style.SHORT);
NumberFormat longFormatter = NumberFormat.getCompactNumberInstance(Locale.US, NumberFormat.Style.LONG);
String compactNumberShortFormat = shortFormatter.format(1_000_000);
String compactNumberLongFormat = longFormatter.format(1_000_000) ;
System.out.println(compactNumberShortFormat); // Output: 1M
System.out.println(compactNumberLongFormat); // Output: 1 million
3. Parsing Numbers
3.1 Parse String to Number, Currency, and Percentage Values
The NumberFormat.parse() method converts formatted strings back into numbers.
NumberFormat numberFormatter = NumberFormat.getInstance();
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(Locale.US);
NumberFormat percentFormatter = NumberFormat.getPercentInstance();
String numStr = "1,234.56";
String currencyStr = "$1,234.56";
String percentStr = "75%";
Number parsedNumber = numberFormatter.parse(numStr);
Number parsedCurrency = currencyFormatter.parse(currencyStr);
Number parsedPercentage = percentFormatter.parse(percentStr);
System.out.println(parsedNumber); // Output: 1234.56
System.out.println(parsedCurrency); // Output: 1234.56
System.out.println(parsedPercentage); // Output: 0.75
The parse() method will throw a ParseException if the number is not properly formatted.
3.2 Parse String to BigDecimal
The DecimalFormat
class allows precise control over number formatting, including decimal places and thousands separator.
String numStr = "1,234.56";
DecimalFormat decimalFormatter = new DecimalFormat("#,###.##");
decimalFormatter.setParseBigDecimal(true);
BigDecimal bigDecimal = (BigDecimal) decimalFormatter.parse(numStr);
System.out.println(bigDecimal); // Output: 1234.56
4. Conclusion
Java provides several powerful ways to format numbers, including DecimalFormat
and NumberFormat
for locale-aware formatting.
- Use
NumberFormat
for currency, percentage, and general formatting. - Use
DecimalFormat
for custom patterns.
You can find the complete code of this article here in GitHub.