Title: Formatting Output
1Formatting Output
- For a pleasant interaction with the user
2Formatting Output
0
Two classes that allow us to format decimal
number output
- DecimalFormat
- NumberFormat static class
- printf method
import java.text.
3Decimal Format
0
- The DecimalFormat class can be used to format a
floating point value. - It allows you to specify the number of decimal
places that you want
4Constructor
DecimalFormat decFor new DecimalFormat(String
pattern)
- The pattern may contain
- One period which corresponds with the decimal
- Any symbols before and/or after the number
specifications - All of this should be enclosed in quotes
5The 0 and the
- 0 specifies that a 0 should be printed even if
there is no value specified for this position. - specifies that a number should be printed if
there is any, otherwise leave blank.
See java/Strings NumFormat.java
6Number and Decimal Patterns
Numbers will be represented either by or
0 Example DecimalFormat decFor4 new
DecimalFormat(".") DecimalFormat decFor
new DecimalFormat(0.00") double d1
0.099 double d2 27 System.out.println(decFor4
.format(d1)) System.out.println(decFor4.format(d2
)) System.out.println(decFor.format(d1)) System
.out.println(decFor.format(d2))
.099 27.0
0.10 27.00
7No Decimals
Specifying NO decimal places Example DecimalFo
rmat df new DecimalFormat(0.") double d1
0.099 double d2 27 System.out.println(df.form
at(d1)) System.out.println(df.format(d2))
0. 27.
8More Pattern Components
- The pattern may contain
- One period which corresponds with the decimal
- Any symbols before and/or after the number
- All of this should be enclosed in quotes
9Examples
double d1 0.023 double d2
123.456789 double d3 0.0098
DecimalFormat df2 new DecimalFormat(" 0.00")
DecimalFormat df3 new DecimalFormat("00.0
ft") System.out.println(df2.format(d
1)) System.out.println(df2.format(d2))
System.out.println(df2.format(d3))
System.out.println(df3.format(d1
)) System.out.println(df3.format(d2))
System.out.println(df3.format(d3))
0.02 123.46 0.01
00.023 ft 123.4568 ft 00.0098 ft
10Questions????
DecimalFormat
import java.text.