Skip to main content

String Formatting And Parsing

Number Formatting

Learn Java number formatting with NumberFormat and DecimalFormat classes. Master currency formatting, decimal places, thousands separators, and locale-specific displays. Complete tutorial with examples for professional Java string manipulation and number display.

When working with numbers in Java, there are times when you want to display them in a more human-readable or specific format, like adding commas, displaying a certain number of decimal places, or showing currency symbols. Java provides two powerful tools for this: NumberFormat and DecimalFormat. These tools make it easy to format numbers based on your needs.

Why Format Numbers?

Imagine you're working on an app that shows prices. You don't want numbers like "1234567.89" to appear without proper formatting. It would look much better as "1,234,567.89". Also, depending on where your users are located, you might need to format numbers differently (for example, showing currency symbols like $ or ).

When working with numbers in Java, there are times when you want to display them in a more human-readable or specific format, like adding commas, displaying a certain number of decimal places, or showing currency symbols. Java provides two powerful tools for this: NumberFormat and DecimalFormat. These tools make it easy to format numbers based on your needs.

Using NumberFormat for Localized Formatting

NumberFormat is a class in Java that helps you format numbers based on the local conventions (like currency symbols, thousands separators, etc.). It automatically adapts to the location (also called locale) you specify, making it great for displaying numbers in a way that’s familiar to users from different countries.

Basic Usage of NumberFormat

To format numbers like currencies or percentages, you can use NumberFormat. This class has built-in methods for common formats like:

  • Currency: Adds currency symbols (like $) and formats the number properly.
  • Percentage: Formats numbers as percentages (like 50%).
  • General Number: Adds commas or adjusts decimals based on the locale.

Formatting as Currency

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

double price = 1234567.89;

// Get the currency instance for the US locale
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(Locale.US);
String formattedPrice = currencyFormatter.format(price);

System.out.println(formattedPrice);  // Outputs: "$1,234,567.89"

In this example:

  • NumberFormat.getCurrencyInstance(Locale.US) tells Java to format the number as US currency.
  • The result is formatted with a dollar sign ($) and commas.

You can easily change the locale to format numbers for other countries.

Formatting for Another Locale

NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(Locale.GERMANY);
String formattedPrice = currencyFormatter.format(price);

System.out.println(formattedPrice);  // Outputs: "1.234.567,89 €"

Here, the same number is formatted for Germany, where commas and periods are used differently, and the euro symbol () is added.

Formatting as a Percentage

double fraction = 0.75;

NumberFormat percentFormatter = NumberFormat.getPercentInstance();
String formattedPercent = percentFormatter.format(fraction);

System.out.println(formattedPercent);  // Outputs: "75%"

In this case, NumberFormat.getPercentInstance() automatically multiplies the number by 100 and adds a percent sign (%).

Custom Number Formatting Using DecimalFormat

While NumberFormat is great for common use cases, you might want more control over exactly how a number is displayed. This is where DecimalFormat comes in. DecimalFormat allows you to specify custom patterns for how you want numbers to be formatted.

Basic Usage of DecimalFormat

DecimalFormat lets you define patterns using symbols like:

  • 0: Represents a digit (shows leading zeros if necessary).
  • #: Represents a digit (does not show extra zeros).
  • ,: Adds a thousands separator.
  • .: Adds a decimal point.

Formatting with Thousands Separator

import java.text.DecimalFormat;

double number = 1234567.89;

// Define a pattern to format with commas and two decimal places
DecimalFormat df = new DecimalFormat("#,###.00");
String formattedNumber = df.format(number);

System.out.println(formattedNumber);  // Outputs: "1,234,567.89"

In this example:

  • #,###.00 tells Java to:
    • Use commas for thousands (#,###).
    • Always show two decimal places (.00), even if the number is whole.

Formatting with Leading Zeros

double number = 45.678;

// Define a pattern to display leading zeros and three decimal places
DecimalFormat df = new DecimalFormat("0000.000");
String formattedNumber = df.format(number);

System.out.println(formattedNumber);  // Outputs: "0045.678"

Here, the pattern 0000.000 means:

  • The number should always be at least four digits long before the decimal point, and it should be filled with leading zeros if necessary.
  • After the decimal point, three decimal places will be shown.

Formatting Without Extra Decimal Places

If you don’t want unnecessary decimal places to show, use the # symbol instead of 0.

double number = 45.6;

DecimalFormat df = new DecimalFormat("#.##");
String formattedNumber = df.format(number);

System.out.println(formattedNumber);  // Outputs: "45.6"

The pattern #.## means: Show up to two decimal places, but don’t force zeros to appear if they’re unnecessary.

Summary

  • NumberFormat is used for localized formatting (currency, percentages, etc.), and it automatically adjusts numbers based on the locale (country).
    • NumberFormat.getCurrencyInstance() formats numbers as currency.
    • NumberFormat.getPercentInstance() formats numbers as percentages.
  • DecimalFormat allows for custom formatting using patterns like:
    • #,###.00: Adds commas and always shows two decimal places.
    • 0000.000: Ensures leading zeros and three decimal places.

Using these tools, you can ensure that your numbers are displayed in a clean, readable, and context-appropriate format for your users!