100 likes | 128 Views
Formatting Output. For a pleasant interaction with the user. Formatting Output. 0. Two classes that allow us to format decimal number output. DecimalFormat NumberFormat static class printf method. import java.text.*;. Decimal Format. 0.
E N D
Formatting Output For a pleasant interaction with the user
Formatting Output 0 Two classes that allow us to format decimal number output • DecimalFormat • NumberFormat static class • printf method import java.text.*; Blanca Polo ICS111
Decimal 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 Blanca Polo ICS111
Variable name parameter class Constructor 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 Blanca Polo ICS111
The 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 Blanca Polo ICS111
decimal Number 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 Blanca Polo ICS111
No Decimals Specifying NO decimal places… Example: DecimalFormat df = new DecimalFormat(”0."); double d1 = 0.099; double d2 = 27; System.out.println(df.format(d1)); System.out.println(df.format(d2)); 0. 27. Blanca Polo ICS111
More 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 Blanca Polo ICS111
Examples 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(d1)); 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 Blanca Polo ICS111
Questions???? DecimalFormat # import java.text.*; Blanca Polo ICS111