How to format a dollar amount in Java

Number can be formatted using the NumberFormat class available in the java.text package.

Syntax:

final double doubleToFormat = 1000000.01;
formatted = NumberFormat.getNumberInstance( Locale.ENGLISH ).format(doubleToFormat);

Here is an example creating a String using the NumberFormat class for the English locale. The method format is called with an integer and a double the formatted String is then written in the output.

Create the following java file:

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

public class DollarAmountFormatting {

	public static void main(String[] argv){
	    final int integerToFormat = 1000000;
	    String formatted = NumberFormat.getIntegerInstance( Locale.ENGLISH ).format(integerToFormat);
		
	    System.out.println( "Formatted dollar amount: $" + formatted ); 

	    final double doubleToFormat = 1000000.01;
	    formatted = NumberFormat.getNumberInstance( Locale.ENGLISH ).format(doubleToFormat);
		
	    System.out.println( "Formatted dollar amount: $" + formatted ); 
	}
	
}

The output will be:

Formatted dollar amount: $1,000,000
Formatted dollar amount: $1,000,000.01


References:

Java 7 System

Recent Comments