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 parse negative number in parentheses?

In financial application negative numbers are often represented in parentheses. In this post we will learn how we can parse or convert the negative number in parentheses to produce the represented number value. To parse text / string to a number we can use the java.text.DecimalFormat class.

Beside number in parentheses, in this example we also parse negative number that use the minus sign with the currency symbol like $. Let’s jump to the code snippet below:

package org.kodejava.text;

import java.text.DecimalFormat;

public class NegativeNumberParse {
    // Pattern for parsing 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) throws Exception {
        DecimalFormat df = new DecimalFormat(PATTERN1);

        String number1 = "(1000)";
        String number2 = "(1,500.99)";

        System.out.println("number1 = " + df.parse(number1));
        System.out.println("number2 = " + df.parse(number2));

        df = (DecimalFormat) DecimalFormat.getInstance();
        df.applyPattern(PATTERN2);

        String number3 = "-$1000";
        String number4 = "-$1,500.99";

        System.out.println("number3 = " + df.parse(number3));
        System.out.println("number4 = " + df.parse(number4));
    }
}

And here are the results of our code snippet above:

number1 = -1000
number2 = -1500.99
number3 = -1000
number4 = -1500.99

If you need to display or format negative numbers in parentheses you can take a look at the following example How do I display negative number in parentheses?.

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 number format symbols?

You can use the DecimalFormatSymbols class to change the symbols that appear in the formatted numbers. These symbols include the decimal separator which can be changed using the setDecimalSeparator(), the grouping separator which can be change using the setGroupingSeparator() method. You can also alter the minus sign, and the percent sign, among others.

package org.kodejava.text;

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

public class NumberFormatSymbol {
    public static void main(String[] args) {
        DecimalFormat formatter;
        String pattern = "###,###.##";
        double number = 123456.789;

        // Create a DecimalFormatSymbols object for the United States
        // locale.
        DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale.US);

        // Create a format object with the given pattern without
        // change the locale dfs then format the given value.
        formatter = new DecimalFormat(pattern);
        String before = formatter.format(number);

        // Change the decimal separator and grouping separator symbol.
        dfs.setDecimalSeparator(',');
        dfs.setGroupingSeparator('.');
        dfs.setMinusSign('-');
        dfs.setPercent('%');

        // Create a format object with the given pattern and symbol
        // then format the given value.
        formatter = new DecimalFormat(pattern, dfs);
        String after = formatter.format(number);

        System.out.println("before: " + before + " | after: " + after);
    }
}