The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > java.text  [26 examples] > Numbers  [5 examples]

e312. Formatting and Parsing a Number for a Locale

A formatted number consists of locale-specific symbols such as the decimal point. For example, a Canadian decimal point is a dot while a German decimal point is a comma. This example demonstrates how to format a number for a particular locale.
    // Format for CANADA locale
    Locale locale = Locale.CANADA;
    String string = NumberFormat.getNumberInstance(locale).format(-1234.56);  // -1,234.56
    
    // Format for GERMAN locale
    locale = Locale.GERMAN;
    string = NumberFormat.getNumberInstance(locale).format(-1234.56);   // -1.234,56
    
    // Format for the default locale
    string = NumberFormat.getNumberInstance().format(-1234.56);
    
    
    // Parse a GERMAN number
    try {
        Number number = NumberFormat.getNumberInstance(locale.GERMAN).parse("-1.234,56");
        if (number instanceof Long) {
            // Long value
        } else {
            // Double value
        }
    } catch (ParseException e) {
    }

 Related Examples
e311. Formatting a Number Using a Custom Format
e313. Formatting a Number in Exponential Notation
e314. Formatting and Parsing Locale-Specific Currency
e315. Formatting and Parsing a Locale-Specific Percentage

See also: Dates    Messsages    Times    Words and Sentences   


© 2002 Addison-Wesley.