How do I format a number as percentage with fraction digits?

In Java, the NumberFormat class of java.text package can be used to format numbers. For formatting a number as a percentage string with fraction digits, you can use the getPercentInstance() method that returns a percentage format for the current default Locale.

Here is a sample code snippet showing how to format a number as a percentage string with two digits of fractions:

package org.kodejava.text;

import java.text.NumberFormat;

public class FormatPercentage {
    public static void main(String[] args) {
        double number = 0.12345;

        // Get an instance of NumberFormat for percentage
        NumberFormat percentFormat = NumberFormat.getPercentInstance();

        // Set the fraction digits - change this value to control the
        // number of fraction digits.
        percentFormat.setMinimumFractionDigits(2); // set the minimum
        percentFormat.setMaximumFractionDigits(4); // set the maximum

        // Format the number as a percentage
        String formattedPercent = percentFormat.format(number);

        System.out.println("Number as percentage: " + formattedPercent);
    }
}

Output:

Number as percentage: 12.345%

In the above example, 0.12345 will be formatted as 12.35% because we have set the MinimumFractionDigits to 2 which means up to two decimal points will be included in the formatted percentage. If we also set the MaximumFractionDigits it will allow us to have up to four decimal points in the output value, here we have 12.345%.

Note that the actual percentage is calculated by multiplying the number by 100, so 0.12345 becomes 12.345% and then rounded to 12.35% (because of the fraction digits setting, in this case we only set the minimum fraction digits to two decimal points).

We can also use the DecimalFormat class. The DecimalFormat class in Java is used to format decimal numbers. It is a subclass of NumberFormat and you can customize the format of your number using it.

Here’s a simple example of how you can format a number as a percentage string using DecimalFormat:

package org.kodejava.text;

import java.text.DecimalFormat;

public class DecimalFormatPercentDemo {
    public static void main(String[] args) {
        double number = 0.123;

        // Create a new DecimalFormat instance with a percentage pattern
        DecimalFormat df = new DecimalFormat("#%");

        // Set the number of fraction digits 
        df.setMinimumFractionDigits(2);

        // Format the number into a percentage
        String percentage = df.format(number);

        System.out.println(percentage);
    }
}

This program will output 12.30%

The "#%" pattern means that the number should be formatted as a percentage. And df.setMinimumFractionDigits(2); means that the decimal will be formatted to two places.

The DecimalFormat will automatically multiply our value by 100, which is why 0.123 appears as 12.30%.

How do I display negative number in parentheses?

The code snippet below show us how to display or format negative number in parentheses. We start by defining the number format, the pattern has two parts separated by a semicolon. In the snippet we use the #,##0.00;(#,##0.00) pattern. The pattern after the semicolon will be used to format negative number.

Next we create an instance of DecimalFormat by calling getInstance() method. We apply the format pattern for the formatter object by calling the applyPattern() method of the DecimalFormat instance. To format the number we simply call the format() method and pass the number we are going to format for display or print out.

package org.kodejava.text;

import java.text.DecimalFormat;

public class NegativeNumberFormat {
    // Pattern for formatting negative number.
    public static final String PATTERN1 = "#,##0.00;(#,##0.00)";
    public static final String PATTERN2 = "$#,##0.00;-$#,##0.00";

    public static void main(String[] args) {
        DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance();
        df.applyPattern(PATTERN1);

        // Format using parentheses
        System.out.println("Positive: " + df.format(125));
        System.out.println("Negative: " + df.format(-125));

        // Format using currency symbol and minus sign
        df.applyPattern(PATTERN2);
        System.out.println("Positive: " + df.format(1000));
        System.out.println("Negative: " + df.format(-1000));
    }
}

The result of the code snippet above is:

Positive: 125.00
Negative: (125.00)
Positive: $1,000.00
Negative: -$1,000.00

If you need to parse negative numbers in parentheses to produce the represented number you can see the following example How do I parse negative number in parentheses?.

How do I change the currency symbol?

This example show you how to change the currency symbol for the defined locale using the DecimalFormatSymbols.setCurrencySymbol() method. After changing the currency symbol, the DecimalFormatSymbols instance is passed to the DecimalFormat object which does the formatting.

package org.kodejava.text;

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

public class CurrencyFormatSymbols {
    public static void main(String[] args) {
        double number = 123456.789;

        Locale[] locales = {
                Locale.CANADA, Locale.GERMANY, Locale.UK, Locale.ITALY, Locale.US
        };

        String[] symbols = {"CAD", "EUR", "GBP", "ITL", "USD"};

        for (int i = 0; i < locales.length; i++) {
            // Gets currency's formatted value for each locale
            // without change the currency symbol
            DecimalFormat formatter =
                    (DecimalFormat) NumberFormat.getCurrencyInstance(locales[i]);
            String before = formatter.format(number);

            // Create a DecimalFormatSymbols for each locale and sets
            // its new currency symbol.
            DecimalFormatSymbols symbol = new DecimalFormatSymbols(locales[i]);
            symbol.setCurrencySymbol(symbols[i]);

            // Set the new DecimalFormatSymbols into formatter object.
            formatter.setDecimalFormatSymbols(symbol);

            // Gets the formatted value
            String after = formatter.format(number);
            System.out.println(locales[i].getDisplayCountry() +
                    " | before: " + before + " | after: " + after);
        }
    }
}

Here is are the result of our program:

Canada | before: $123,456.79 | after: CAD123,456.79
Germany | before: 123.456,79 € | after: 123.456,79 EUR
United Kingdom | before: £123,456.79 | after: GBP123,456.79
Italy | before: € 123.456,79 | after: ITL 123.456,79
United States | before: $123,456.79 | after: USD123,456.79

How do I change DecimalFormat pattern?

To change the pattern use by the DecimalFormat when formatting a number we can use the DecimalFormat.applyPattern() method call. In this example we use three different patterns to format the given input number. The pattern determines what the formatted number looks like.

package org.kodejava.text;

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

public class FormatterPattern {
    public static void main(String[] args) {
        String[] patterns = {"###,###,###.##", "000000000.00", "$###,###.##"};

        double before = 1234567.899;

        // To obtain a NumberFormat for a specific locale,
        // including the default locale, call one of NumberFormat's
        // factory methods, such as getNumberInstance(). Then cast
        // it into a DecimalFormat.
        DecimalFormat format =
                (DecimalFormat) NumberFormat.getNumberInstance(Locale.UK);
        for (String pattern : patterns) {
            // Apply the given pattern to this Format object
            format.applyPattern(pattern);

            // Gets the formatted value
            String after = format.format(before);

            System.out.printf("Input: %s, Pattern: %s, Output: %s%n",
                    before, pattern, after);
        }
    }
}

The output of the program shown below:

Input: 1234567.899, Pattern: ###,###,###.##, Output: 1,234,567.9
Input: 1234567.899, Pattern: 000000000.00, Output: 001234567.90
Input: 1234567.899, Pattern: $###,###.##, Output: $1,234,567.9

How do I format number as percentage string?

The NumberFormat.getPercentInstance() method returns a percentage format for the specified locale. In this example we will format the number as percentage using the Locale.US locale.

package org.kodejava.text;

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

public class LocalePercentageFormat {
    public static void main(String[] args) {
        // Format percentage for Locale.US locale with this formatter,
        // a decimal fraction such as 0.75 is displayed as 75%
        double number = 0.25;
        NumberFormat format = NumberFormat.getPercentInstance(Locale.US);
        String percentage = format.format(number);
        System.out.println(number + " in percentage = " + percentage);
    }
}

The following line is the output of the program:

0.25 in percentage = 25%