Wednesday, July 26, 2006
How to format numbers in Java
It appears that formatting numbers in Java is quite a challenge. Here is what I found out so far.
If you simply need to output a real value with given number of digits, the simplest way to do so would be this (make sure to import java.text.*):
DecimalFormat form = new DecimalFormat ( "0.000" ); System.out.println ( form.format(-Math.sqrt(2)));
This will print
-1.414
The most important feature of DecimalFormat() is that you can take advantage of pre-defined "factory methods", by calling functions
form = NumberFormat.getXXXInstance(locale);
where XXX is ether empty, or one of "Integer", "Currency", or "Percent".
You can also use form.parse() to parse strings in corresponding format, and form.toPattern() to access pre-defined locale-specific patterns.
See this help page for more on formats and locales.
Labels: java