Lesson 3.6 Output Formatting
Formatting Numeric Output
In Lesson 3.5, "Numeric Input", you learned how to turn the String "123" into the integer 123: how to convert from human-readable numbers to machine-readable.
In this section, we'll go the other direction, taking your int, float, and double variables, and making them fit for human consumption.
The Direct Approach
The easiest way to convert a number to a String is to use String concatenation. In the lesson on "Characters", you saw how String concatenation could be used to "paste" two Strings together to form a third, like this:
String favFood = "spam";
String msg = "My favorite food is";
String combo = msg + " " + favFood; |
String concatenation can also be used to automatically convert numbers--of any type--into Strings as well, like this:
double d = 3.145;
int i = 72;
float f = 5.9e3F;
String s = " d = " + d +
", i = " + i +
", f = " + f; |
When you run this applet, it produces the String shown here.
|
| When you use String concatenation and allow Java to automatically convert your variables, you have no real control over the way in which the number is presented. |
Built-in Formats
Numeric, currency, and percentage formatting is the province of the java.text package which was introduced in Java 1.1. In earlier versions of Java, you had to make do with the direct method or do the low-level coding yourself. To use any of these more advanced formatting features you must add this import statement to the beginning of your program:
import java.text.*;
Using Java's NumberFormat class, you can automatically format numbers according to the local conventions in use where your application is run. If your application is run in Germany, for instance, your number will automatically use the comma as the decimal separator and the period as the grouping separator--just the opposite of the custom in the US.
The NumberFormat Class
The first step is to create a NumberFormat object. You have your choice of three built-in formatting styles: a generic number formatter, a currency formatter, and a percentage formatter.
Unlike the earlier objects you've used, you don't use the new operator to construct your NumberFormat objects; instead you use very specific methods called factory methods. Under the hood, the factory method uses the new operator, just like you've done all along, but using the factory method makes your code somewhat easier.
The three factory methods you use to create built-in format objects are the getNumberInstance(), getCurrencyInstance(), and getPercentInstance(). Here's an example:
| NumberFormat nf, cf, pf;
nf = NumberFormat.getNumberInstance();
cf = NumberFormat.getCurrencyInstance();
pf = NumberFormat.getPercentInstance(); |
Notice that when you use factory methods to create an object, you preceed the method with the name of the class, in this case, NumberFormat.
Using Number Format Objects
To use your NumberFormat object, you simply call its format() method, passing either a double primitive value or a Double object.
Here are the steps you'd use to convert and display the value in a TextField named numTF using the NumberFormat object nf:
- Retrieve the text stored in numTF using getText() .
- Convert the text to a Double object using the Double(String) constructor.
- Convert the Double object to a String using nf.format().
- Display the result in a Label, here called numLbl , using setText().
Here's what that looks like in Java code, along with the necessary code to display the number as a currency amount and as a percentage as well.
String sVal = numTF.getText();
Double bigD = new Double(sVal);
String sFmt = nf.format(bigD);
numLbl.setText(sFmt);
sFmt = cf.format(bigD);
curLbl.setText(sFmt);
sFmt = pf.format(bigD);
pctLbl.setText(sFmt); |
Here is an applet that uses this code. Enter a number into the TextField and press ENTER. Enter some very small numbers and watch how the percent formatter works. Enter some large numbers as well, and notice the default numeric formatting and the currency formatting.
Custom Formatting
If, for some reason, you are not happy with any of the built-in formatter objects, the NumberFormat class has a subclass you can use to create custom formatters: the DecimalFormat class.
To create a DecimalFormat object, you use a constructor, passing it a pattern. The pattern can be quite complex, and you'll have to study the Java documentation if you want to learn all of its capabilities. You can make simple patterns, however, using these four characters:
|
Symbol
|
Pattern Meaning
|
|
#
|
An optional digit. If there is no digit in this position, nothing will print. |
|
0
|
A mandatory digit. If there is no digit in this position, then a zero will print. Use this for leading zeros. |
|
,
|
Separate groups |
|
.
|
Separate decimals |
Any other characters used in the pattern String are reproduced in the output exactly. Here's a short example:
DecimalFormat df;
df = new DecimalFormat("###,##0.00"); |
Use the format() method to produce a String, just as you would with the built-in formatter objects.
| s = df.format(someValue); |
Something to Talk About
How would you create a custom formatter object, using the DecimalFormat class and its constructor, that displays four mandatory places to the right of the decimal, and group the digits to the left of the decimal in groups of four?
What's the result of using your formatter's format() method with the numbers:
- 734952.73
- 23
- 43593234.982123
This is the last section of this lesson.
|