Class 1, Part 2 |
Intro to Java 30-IT-396 |
|
Formatting Output
-
System.out.println(String) prints the desired string to standard output
(often the console window), and System.out.println(String) prints the String,
followed by a new line.
-
You can use the java.text.NumberFormat class to format numbers.
-
NumberFormat.getNumberInstance() formats numbers with commas and
decimals.
-
NumberFormat.getCurrencyInstance() formats numbers for currnecy,
with a dollar sign and two digits after the decimal.
-
NumberFormat.getPercentInstance() formats numbers as a percentage,
with the percent sign at the end.
-
You can enter a locale in the get methods above to set the number instance
for a specific country. This will allow your Java program to use
notation from other countries.
-
Use the get methods mentioned above to create an object of the NumberFormat
class. Then, you can use that object as many times as you need to
format multiple numbers.
-
Use the format() method of the NumberFormat class to
actually format the number. This method returns a String object.
-
Other handy methods:
-
setMaximumFractionDigits() sets the maximum number of digits after the
decimal before the values are truncated.
-
setMinimumFractionDigits() sets the minimum number of digits after the
decimal. It will zero-fill if necessary.
-
setMaximumIntegerDigits() and setMinimumIntegerDigits() does the same for
integers. Their usefullness is somewhat limited.
-
NumberFormat has a cousin for formatting dates, DateFormat. We'll
talk about him later.
Example


Created by: Brandan
Jones January 4, 2002