Tuesday, July 13, 2010

Format a Decimal Number (Double) in Java

To format a decimal number (double) in Java we can use the java.text.DecimalFormat class. The following code example demonstrates formatting the number of decimal digits and the thousands separator of a decimal number.


import java.text.DecimalFormat;

// Java 1.4+ Compatible
//
// The following example code demonstrates converting a number 
// (double) into a formatted String setting the number of digits 
// after the decimal place and the separator between the thousands groups
//
public class FormatDecimalNumber {

public static void main(String[] args) {

// circumference of earth in km
double number = 40075.1646;

// thousands separator, three decimal places
DecimalFormat df = new DecimalFormat("###,###.###");
System.out.println(df.format(number));

// no thousands separator, two decimal places
df = new DecimalFormat(".##");
System.out.println(df.format(number));

}
}



Here is the output of the example code:
40,075.165
40075.16

No comments: