Java Reference
In-Depth Information
The parse method is also used for parsing currency. Study the following code and see if
you can determine its output:
29. NumberFormat cf = NumberFormat.getCurrencyInstance();
30. try {
31. String amt = “$12,345.99”;
32. double value = (Double) cf.parse(amt);
33. System.out.println(value);
34. }catch(ParseException e) {
35. e.printStackTrace();
36. }
The currency string ”$12,345.99” on line 31 contains a dollar sign and a comma. The
parse method strips out the characters and converts the value to a number. Assuming a
U.S. locale, the output of the code is
12345.99
The return value of parse is a Number object. Number is the parent class of all the java
.lang wrapper classes, so the return value can be cast to its appropriate data type. On line
32, the Number is cast to a Double and then automatically unboxed into a double .
The NumberFormat and DecimalFormat classes have other features and capabilities, but
the topics covered in this section address the content you need to know for the SCJP exam.
The next section discusses how to format and parse dates.
Format and Parse Dates
The java.text.DateFormat class is an abstract class that formats and parses dates and
times for a specifi c locale. Similar to NumberFormat , DateFormat objects are obtained by
invoking one of the static factory methods in the DateFormat class. You can create a date
format for working with just dates, or a date/time format for working with dates and times,
as follows:
public static final DateFormat getDateInstance() is intended for formatting
dates in the default locale.
public static final DateFormat getDateInstance(int style, Locale loc) gets
the date formatter with the specified style and locale. The possible formatting styles
are FULL , LONG , MEDIUM , and SHORT , static constants defined in the DateFormat class.
public static final DateFormat getTimeInstance() is used for formatting times in
the default locale.
public static final DateFormat getTimeInstance(int style, Locale loc) gets
the time formatter with the specified style and locale. The possible time formatting
styles are FULL , LONG , MEDIUM , and SHORT .
public static final DateFormat getDateTimeInstance() is used for formatting
dates and times in the default locale.
Search WWH ::




Custom Search