Number can be formatted using the NumberFormat
class available in the java.text package.
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.
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 ); } }
Formatted dollar amount: $1,000,000 Formatted dollar amount: $1,000,000.01