Formatting Output - PowerPoint PPT Presentation

About This Presentation
Title:

Formatting Output

Description:

Blanca Polo. ICS111. 3. Decimal Format ... Blanca Polo. ICS111. 4. Constructor. DecimalFormat decFor = new DecimalFormat(String pattern) ... – PowerPoint PPT presentation

Number of Views:44
Avg rating:3.0/5.0
Slides: 11
Provided by: blanc9
Learn more at: http://www2.hawaii.edu
Category:

less

Transcript and Presenter's Notes

Title: Formatting Output


1
Formatting Output
  • For a pleasant interaction with the user

2
Formatting Output
0
Two classes that allow us to format decimal
number output
  • DecimalFormat
  • NumberFormat static class
  • printf method

import java.text.
3
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

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

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
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
7
No 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.
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
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(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
10
Questions????
DecimalFormat

import java.text.
Write a Comment
User Comments (0)
About PowerShow.com