Formatting Numbers


double value = 1623542.765; NumberFormat numberFormatter; String formattedValue; numberFormatter = NumberFormat.getNumberInstance(); formattedValue = numberFormatter.format(value); System.out.format("%s%n", formattedValue);



In most applications, there is a need to display numbers. Fortunately, Java has built-in support for formatting numbers so that they will look as you want them to when you display them in your application.

This phrase will generate the following formatted number as output:

1,623,542.765


In this phrase, we use the NumberFormat class to format a double value into a comma separated string representation of its value. The NumberFormat class is found in the java.text package and is also very useful for code that you will internationalize. The NumberFormat class supports the formatting of numbers and currency, and it also knows how to represent numbers and currency in different locales.

The NumberFormat class can also be used to easily format percent values for display. Here, we show how you can use the NumberFormat class to format a percent for display:

double percent = 0.80; NumberFormat percentFormatter; String formattedPercent; percentFormatter = NumberFormat.getPercentInstance(); formattedPercent = percentFormatter.format(percent); System.out.format("%s%n", formattedPercent);


The output of this code will be

80%


The NumberFormat class also has a parse() method that you can use to parse strings containing numbers into a Number object, from which you can get a numeric type.

JDK1.5 introduced a java.util.Formatter class, which is a general-purpose formatting object that can format a wide variety of types. In addition to numbers, this class can also format dates and times. This class is documented very well in the JDK1.5 documentation at http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html.

JDK1.5 also added two utility methods to the java.io.PrintStream class for easy formatting of an OutputStream. The new methods are the format() and printf() methods. Both of these methods take a format string and a variable number of Object arguments as input parameters. These methods are very similar to the traditional printf and scanf methods of formatting strings in the C language. For details on using these methods, refer to the JDK1.5 documentation at http://java.sun.com/j2se/1.5.0/docs/api/java/io/PrintStream.html.

In the next phrase, we show how you can format currency values for display, also using the NumberFormat class.




JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net