How do I use NumberFormat to format a percent?
Author: Deron Eriksson
Description: This Java tutorial describes how to use NumberFormat to format a percentage.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)


To format a percentage representation of a number, we can use NumberFormat.getPercentInstance() to get a format object and call various methods on the format object to set the percentage format. We can then pass our number to the format method, which returns the percentage representation of the number. This is demonstrated in the PercentFormatTest class.

PercentFormatTest.java

package test;

import java.text.NumberFormat;

public class PercentFormatTest {

	public static void main(String[] args) throws Exception {

		double num = 0.5267;

		NumberFormat defaultFormat = NumberFormat.getPercentInstance();
		defaultFormat.setMinimumFractionDigits(1);
		System.out.println("Percent format: " + defaultFormat.format(num));

	}

}

The console output of PercentFormatTest is shown here:

Percent format: 52.7%