Tuesday, July 13, 2010

Format a Decimal Number According to Local Formatting Standards in Java

To format a decimal number (double) according to different number formatting standards in different countries we can use the java.text.DecimalFormat, java.text.NumberFormat, and java.util.Locale classes. The following code example demonstrates formatting a decimal number in various country-specific styles.


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

//Java 1.4+ Compatible
//
// The following example code demonstrates converting a number 
// (double) into a formatted String according to different 
// number formatting standards in various countries
//
public class FormatDecimalLocalFormat {

public static void main(String[] args) {

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

// Germany
DecimalFormat df = (DecimalFormat) NumberFormat.getInstance(Locale.GERMAN);
System.out.println(df.format(number));

// United states
df = (DecimalFormat) NumberFormat.getInstance(Locale.US);
System.out.println(df.format(number));

// China
df = (DecimalFormat) NumberFormat.getInstance(Locale.CHINESE);
System.out.println(df.format(number));

// France
df = (DecimalFormat) NumberFormat.getInstance(Locale.FRENCH);
System.out.println(df.format(number));

}
}



Here is the output of the example code:
40.075,169
40,075.169
40,075.169
40 075,169

No comments: