Presentation is loading. Please wait.

Presentation is loading. Please wait.

Formatting Output For a pleasant interaction with the user.

Similar presentations


Presentation on theme: "Formatting Output For a pleasant interaction with the user."— Presentation transcript:

1 Formatting Output For a pleasant interaction with the user

2 Blanca Polo ICS111 2 Formatting Output DecimalFormat NumberFormat static class printf method Two classes that allow us to format decimal number output import java.text.*;

3 Blanca Polo ICS111 3 Decimal Format 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

4 Blanca Polo ICS111 4 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 class parameterVariable name

5 Blanca Polo ICS111 5 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

6 Blanca Polo ICS111 6 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 decimal

7 Blanca Polo ICS111 7 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.

8 Blanca Polo ICS111 8 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

9 Blanca Polo ICS111 9 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

10 Blanca Polo ICS111 10 Questions????


Download ppt "Formatting Output For a pleasant interaction with the user."

Similar presentations


Ads by Google