Tuesday, 31 July 2012

Java Number Formatting Summary

How to Add Leading Zero's to a Number?

To format a number with 10 digits (for example) and add leading 0 as necessary:
long l = 45294324;
String s = String.format("%010d", l);
System.out.println(s);
For multiple formatting in a same string:
String s2 = String.format("%03d-%05d", 45, 2);
System.out.println(s2);
The output is:

  0045294324
  045-00002

How to Perform Currency Formatting?

Java offers NumberFormat instances for specific Locales:
NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US);
System.out.println(nf.format(445.34256));

nf = NumberFormat.getCurrencyInstance(Locale.JAPAN);
System.out.println(nf.format(445.34256));

nf = NumberFormat.getCurrencyInstance(Locale.GERMANY);
System.out.println(nf.format(445.34256));

The above code snippet produces the following:

  $445.34
  ¥445
  445,34 €

More about Java Internationalization here.