Did this blog help you solve a problem? Tip me with Bitcoins at: 17dQktcAmU4urXz7tGk2sbuiCqykm3WLs6

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);

// United states
df = (DecimalFormat) NumberFormat.getInstance(Locale.US);

// China
df = (DecimalFormat) NumberFormat.getInstance(Locale.CHINESE);

// France
df = (DecimalFormat) NumberFormat.getInstance(Locale.FRENCH);


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

No comments: