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("###,###.###");

// no thousands separator, two decimal places
df = new DecimalFormat(".##");


Here is the output of the example code:

No comments: