The i18n Cookbook - recipies for a global society

  • java cookbook
  • about the author
Home › Java Internationalization Cookbook › Numerical Systems

Java Cookbook

  • Java Internationalization Cookbook
    • Locales
    • Dates and Times
    • Numerical Systems
      • Format and parse an integer
      • Format and parse a decimal
      • Format and parse a percent
      • Format and parse a currency
      • Format Ordinal Numbers
      • Parse a spelled-out number
      • Spell out a numeric value
      • Use a non-default currency
    • Misc
    • Resource Bundles
    • Unicode, Transliteration, and Charactersets

Format and parse a currency

Problem:

You want to format and parse localized currency values.

Solution:

Currency formatting at its most basic is straight forward in Java programming.  Simply retrieve a currency instance of the NumberFormat class and format your number.

 

To format a currency for Japanese for Japan:

//Get a locale.
Locale ja = new Locale("ja","JP");
//Get a currency instance
NumberFormat nf = NumberFormat.getCurrencyInstance(ja);
//format and output.  Notice the rounding is limited to two place on the output.  This is
//Governed by the currency
String f = nf.format(123456.789);
System.out.println(f);

//Parse the value.  We must handle the potential ParseException
try {
    System.out.println(nf.parse("¥123,457"));
} catch (ParseException e) {
    e.printStackTrace();
}

 


The output:

¥123,457
123457

 

Currencies  have a rounding increment that is also important.  A US dollar has cents, and so a currency should be rounded two decimal places.  A Japanese Yen should be rounded to the nearest integer.  If you specify a currency other than the default for the locale the rounding will reflect the locale and not the currency.

 

‹ Format and parse a percent up Format Ordinal Numbers ›
  • currency
  • format
  • numberformat
  • parse
  • Printer-friendly version
  • Add new comment

If you are testing any of these recipes in Eclipse and the characters are not displaying correctly in your console visit http://i18ncookbook.com/eclipse_settings.

This site is ad supported.  I hope you find something among our sponsors worth clicking. ;)

i18n search

Google
Custom Search

Search

Tags in Tags

calendar date icu4j Java Locale number format numberformat parse spellout timezone transliteration transliterator
more tags

User login

  • Create new account
  • Request new password
  • java cookbook
  • about the author