KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > java > text > NumberFormat


1 /*
2  * @(#)NumberFormat.java 1.65 04/05/10
3  *
4  * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
5  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6  */

7
8 /*
9  * (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
10  * (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved
11  *
12  * The original version of this source code and documentation is copyrighted
13  * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These
14  * materials are provided under terms of a License Agreement between Taligent
15  * and Sun. This technology is protected by multiple US and International
16  * patents. This notice and attribution to Taligent may not be removed.
17  * Taligent is a registered trademark of Taligent, Inc.
18  *
19  */

20
21 package java.text;
22
23 import java.io.InvalidObjectException JavaDoc;
24 import java.io.IOException JavaDoc;
25 import java.io.ObjectInputStream JavaDoc;
26 import java.io.ObjectOutputStream JavaDoc;
27 import java.math.BigInteger JavaDoc;
28 import java.util.Currency JavaDoc;
29 import java.util.HashMap JavaDoc;
30 import java.util.Hashtable JavaDoc;
31 import java.util.Locale JavaDoc;
32 import java.util.Map JavaDoc;
33 import java.util.ResourceBundle JavaDoc;
34 import sun.text.resources.LocaleData;
35
36 /**
37  * <code>NumberFormat</code> is the abstract base class for all number
38  * formats. This class provides the interface for formatting and parsing
39  * numbers. <code>NumberFormat</code> also provides methods for determining
40  * which locales have number formats, and what their names are.
41  *
42  * <p>
43  * <code>NumberFormat</code> helps you to format and parse numbers for any locale.
44  * Your code can be completely independent of the locale conventions for
45  * decimal points, thousands-separators, or even the particular decimal
46  * digits used, or whether the number format is even decimal.
47  *
48  * <p>
49  * To format a number for the current Locale, use one of the factory
50  * class methods:
51  * <blockquote>
52  * <pre>
53  * myString = NumberFormat.getInstance().format(myNumber);
54  * </pre>
55  * </blockquote>
56  * If you are formatting multiple numbers, it is
57  * more efficient to get the format and use it multiple times so that
58  * the system doesn't have to fetch the information about the local
59  * language and country conventions multiple times.
60  * <blockquote>
61  * <pre>
62  * NumberFormat nf = NumberFormat.getInstance();
63  * for (int i = 0; i < a.length; ++i) {
64  * output.println(nf.format(myNumber[i]) + "; ");
65  * }
66  * </pre>
67  * </blockquote>
68  * To format a number for a different Locale, specify it in the
69  * call to <code>getInstance</code>.
70  * <blockquote>
71  * <pre>
72  * NumberFormat nf = NumberFormat.getInstance(Locale.FRENCH);
73  * </pre>
74  * </blockquote>
75  * You can also use a <code>NumberFormat</code> to parse numbers:
76  * <blockquote>
77  * <pre>
78  * myNumber = nf.parse(myString);
79  * </pre>
80  * </blockquote>
81  * Use <code>getInstance</code> or <code>getNumberInstance</code> to get the
82  * normal number format. Use <code>getIntegerInstance</code> to get an
83  * integer number format. Use <code>getCurrencyInstance</code> to get the
84  * currency number format. And use <code>getPercentInstance</code> to get a
85  * format for displaying percentages. With this format, a fraction like
86  * 0.53 is displayed as 53%.
87  *
88  * <p>
89  * You can also control the display of numbers with such methods as
90  * <code>setMinimumFractionDigits</code>.
91  * If you want even more control over the format or parsing,
92  * or want to give your users more control,
93  * you can try casting the <code>NumberFormat</code> you get from the factory methods
94  * to a <code>DecimalFormat</code>. This will work for the vast majority
95  * of locales; just remember to put it in a <code>try</code> block in case you
96  * encounter an unusual one.
97  *
98  * <p>
99  * NumberFormat and DecimalFormat are designed such that some controls
100  * work for formatting and others work for parsing. The following is
101  * the detailed description for each these control methods,
102  * <p>
103  * setParseIntegerOnly : only affects parsing, e.g.
104  * if true, "3456.78" -> 3456 (and leaves the parse position just after index 6)
105  * if false, "3456.78" -> 3456.78 (and leaves the parse position just after index 8)
106  * This is independent of formatting. If you want to not show a decimal point
107  * where there might be no digits after the decimal point, use
108  * setDecimalSeparatorAlwaysShown.
109  * <p>
110  * setDecimalSeparatorAlwaysShown : only affects formatting, and only where
111  * there might be no digits after the decimal point, such as with a pattern
112  * like "#,##0.##", e.g.,
113  * if true, 3456.00 -> "3,456."
114  * if false, 3456.00 -> "3456"
115  * This is independent of parsing. If you want parsing to stop at the decimal
116  * point, use setParseIntegerOnly.
117  *
118  * <p>
119  * You can also use forms of the <code>parse</code> and <code>format</code>
120  * methods with <code>ParsePosition</code> and <code>FieldPosition</code> to
121  * allow you to:
122  * <ul>
123  * <li> progressively parse through pieces of a string
124  * <li> align the decimal point and other areas
125  * </ul>
126  * For example, you can align numbers in two ways:
127  * <ol>
128  * <li> If you are using a monospaced font with spacing for alignment,
129  * you can pass the <code>FieldPosition</code> in your format call, with
130  * <code>field</code> = <code>INTEGER_FIELD</code>. On output,
131  * <code>getEndIndex</code> will be set to the offset between the
132  * last character of the integer and the decimal. Add
133  * (desiredSpaceCount - getEndIndex) spaces at the front of the string.
134  *
135  * <li> If you are using proportional fonts,
136  * instead of padding with spaces, measure the width
137  * of the string in pixels from the start to <code>getEndIndex</code>.
138  * Then move the pen by
139  * (desiredPixelWidth - widthToAlignmentPoint) before drawing the text.
140  * It also works where there is no decimal, but possibly additional
141  * characters at the end, e.g., with parentheses in negative
142  * numbers: "(12)" for -12.
143  * </ol>
144  *
145  * <h4><a name="synchronization">Synchronization</a></h4>
146  *
147  * <p>
148  * Number formats are generally not synchronized.
149  * It is recommended to create separate format instances for each thread.
150  * If multiple threads access a format concurrently, it must be synchronized
151  * externally.
152  *
153  * @see DecimalFormat
154  * @see ChoiceFormat
155  * @version 1.65, 05/10/04
156  * @author Mark Davis
157  * @author Helena Shih
158  */

159 public abstract class NumberFormat extends Format JavaDoc {
160
161     /**
162      * Field constant used to construct a FieldPosition object. Signifies that
163      * the position of the integer part of a formatted number should be returned.
164      * @see java.text.FieldPosition
165      */

166     public static final int INTEGER_FIELD = 0;
167
168     /**
169      * Field constant used to construct a FieldPosition object. Signifies that
170      * the position of the fraction part of a formatted number should be returned.
171      * @see java.text.FieldPosition
172      */

173     public static final int FRACTION_FIELD = 1;
174
175     /**
176      * Formats a number and appends the resulting text to the given string
177      * buffer.
178      * The number can be of any subclass of {@link java.lang.Number}.
179      * <p>
180      * This implementation extracts the number's value using
181      * {@link java.lang.Number#longValue()} for all integral type values that
182      * can be converted to <code>long</code> without loss of information,
183      * including <code>BigInteger</code> values with a
184      * {@link java.math.BigInteger#bitLength() bit length} of less than 64,
185      * and {@link java.lang.Number#doubleValue()} for all other types. It
186      * then calls
187      * {@link #format(long,java.lang.StringBuffer,java.text.FieldPosition)}
188      * or {@link #format(double,java.lang.StringBuffer,java.text.FieldPosition)}.
189      * This may result in loss of magnitude information and precision for
190      * <code>BigInteger</code> and <code>BigDecimal</code> values.
191      * @param number the number to format
192      * @param toAppendTo the <code>StringBuffer</code> to which the formatted
193      * text is to be appended
194      * @param pos On input: an alignment field, if desired.
195      * On output: the offsets of the alignment field.
196      * @return the value passed in as <code>toAppendTo</code>
197      * @exception IllegalArgumentException if <code>number</code> is
198      * null or not an instance of <code>Number</code>.
199      * @exception NullPointerException if <code>toAppendTo</code> or
200      * <code>pos</code> is null
201      * @see java.text.FieldPosition
202      */

203     public StringBuffer JavaDoc format(Object JavaDoc number,
204                                StringBuffer JavaDoc toAppendTo,
205                                FieldPosition JavaDoc pos) {
206         if (number instanceof Long JavaDoc || number instanceof Integer JavaDoc ||
207             number instanceof Short JavaDoc || number instanceof Byte JavaDoc ||
208             (number instanceof BigInteger JavaDoc &&
209              ((BigInteger JavaDoc)number).bitLength() < 64)) {
210             return format(((Number JavaDoc)number).longValue(), toAppendTo, pos);
211         } else if (number instanceof Number JavaDoc) {
212             return format(((Number JavaDoc)number).doubleValue(), toAppendTo, pos);
213         } else {
214             throw new IllegalArgumentException JavaDoc("Cannot format given Object as a Number");
215         }
216     }
217
218     /**
219      * Parses text from a string to produce a <code>Number</code>.
220      * <p>
221      * The method attempts to parse text starting at the index given by
222      * <code>pos</code>.
223      * If parsing succeeds, then the index of <code>pos</code> is updated
224      * to the index after the last character used (parsing does not necessarily
225      * use all characters up to the end of the string), and the parsed
226      * number is returned. The updated <code>pos</code> can be used to
227      * indicate the starting point for the next call to this method.
228      * If an error occurs, then the index of <code>pos</code> is not
229      * changed, the error index of <code>pos</code> is set to the index of
230      * the character where the error occurred, and null is returned.
231      * <p>
232      * See the {@link #parse(String, ParsePosition)} method for more information
233      * on number parsing.
234      *
235      * @param source A <code>String</code>, part of which should be parsed.
236      * @param pos A <code>ParsePosition</code> object with index and error
237      * index information as described above.
238      * @return A <code>Number</code> parsed from the string. In case of
239      * error, returns null.
240      * @exception NullPointerException if <code>pos</code> is null.
241      */

242     public final Object JavaDoc parseObject(String JavaDoc source, ParsePosition JavaDoc pos) {
243         return parse(source, pos);
244     }
245
246    /**
247      * Specialization of format.
248      * @see java.text.Format#format
249      */

250     public final String JavaDoc format(double number) {
251         return format(number, new StringBuffer JavaDoc(),
252                       DontCareFieldPosition.INSTANCE).toString();
253     }
254
255    /**
256      * Specialization of format.
257      * @see java.text.Format#format
258      */

259     public final String JavaDoc format(long number) {
260         return format(number, new StringBuffer JavaDoc(),
261                       DontCareFieldPosition.INSTANCE).toString();
262     }
263
264    /**
265      * Specialization of format.
266      * @see java.text.Format#format
267      */

268     public abstract StringBuffer JavaDoc format(double number,
269                                         StringBuffer JavaDoc toAppendTo,
270                                         FieldPosition JavaDoc pos);
271
272    /**
273      * Specialization of format.
274      * @see java.text.Format#format
275      */

276     public abstract StringBuffer JavaDoc format(long number,
277                                         StringBuffer JavaDoc toAppendTo,
278                                         FieldPosition JavaDoc pos);
279
280    /**
281      * Returns a Long if possible (e.g., within the range [Long.MIN_VALUE,
282      * Long.MAX_VALUE] and with no decimals), otherwise a Double.
283      * If IntegerOnly is set, will stop at a decimal
284      * point (or equivalent; e.g., for rational numbers "1 2/3", will stop
285      * after the 1).
286      * Does not throw an exception; if no object can be parsed, index is
287      * unchanged!
288      * @see java.text.NumberFormat#isParseIntegerOnly
289      * @see java.text.Format#parseObject
290      */

291     public abstract Number JavaDoc parse(String JavaDoc source, ParsePosition JavaDoc parsePosition);
292
293     /**
294      * Parses text from the beginning of the given string to produce a number.
295      * The method may not use the entire text of the given string.
296      * <p>
297      * See the {@link #parse(String, ParsePosition)} method for more information
298      * on number parsing.
299      *
300      * @param source A <code>String</code> whose beginning should be parsed.
301      * @return A <code>Number</code> parsed from the string.
302      * @exception ParseException if the beginning of the specified string
303      * cannot be parsed.
304      */

305     public Number JavaDoc parse(String JavaDoc source) throws ParseException JavaDoc {
306         ParsePosition JavaDoc parsePosition = new ParsePosition JavaDoc(0);
307         Number JavaDoc result = parse(source, parsePosition);
308         if (parsePosition.index == 0) {
309             throw new ParseException JavaDoc("Unparseable number: \"" + source + "\"",
310                                      parsePosition.errorIndex);
311         }
312         return result;
313     }
314
315     /**
316      * Returns true if this format will parse numbers as integers only.
317      * For example in the English locale, with ParseIntegerOnly true, the
318      * string "1234." would be parsed as the integer value 1234 and parsing
319      * would stop at the "." character. Of course, the exact format accepted
320      * by the parse operation is locale dependant and determined by sub-classes
321      * of NumberFormat.
322      */

323     public boolean isParseIntegerOnly() {
324         return parseIntegerOnly;
325     }
326
327     /**
328      * Sets whether or not numbers should be parsed as integers only.
329      * @see #isParseIntegerOnly
330      */

331     public void setParseIntegerOnly(boolean value) {
332         parseIntegerOnly = value;
333     }
334
335     //============== Locale Stuff =====================
336

337     /**
338      * Returns a general-purpose number format for the current default locale.
339      * This is the same as calling
340      * {@link #getNumberInstance() getNumberInstance()}.
341      */

342     public final static NumberFormat JavaDoc getInstance() {
343         return getInstance(Locale.getDefault(), NUMBERSTYLE);
344     }
345
346     /**
347      * Returns a general-purpose number format for the specified locale.
348      * This is the same as calling
349      * {@link #getNumberInstance(java.util.Locale) getNumberInstance(inLocale)}.
350      */

351     public static NumberFormat JavaDoc getInstance(Locale JavaDoc inLocale) {
352         return getInstance(inLocale, NUMBERSTYLE);
353     }
354
355     /**
356      * Returns a general-purpose number format for the current default locale.
357      */

358     public final static NumberFormat JavaDoc getNumberInstance() {
359         return getInstance(Locale.getDefault(), NUMBERSTYLE);
360     }
361
362     /**
363      * Returns a general-purpose number format for the specified locale.
364      */

365     public static NumberFormat JavaDoc getNumberInstance(Locale JavaDoc inLocale) {
366         return getInstance(inLocale, NUMBERSTYLE);
367     }
368
369     /**
370      * Returns an integer number format for the current default locale. The
371      * returned number format is configured to round floating point numbers
372      * to the nearest integer using IEEE half-even rounding (see {@link
373      * java.math.BigDecimal#ROUND_HALF_EVEN ROUND_HALF_EVEN}) for formatting,
374      * and to parse only the integer part of an input string (see {@link
375      * #isParseIntegerOnly isParseIntegerOnly}).
376      *
377      * @return a number format for integer values
378      * @since 1.4
379      */

380     public final static NumberFormat JavaDoc getIntegerInstance() {
381         return getInstance(Locale.getDefault(), INTEGERSTYLE);
382     }
383
384     /**
385      * Returns an integer number format for the specified locale. The
386      * returned number format is configured to round floating point numbers
387      * to the nearest integer using IEEE half-even rounding (see {@link
388      * java.math.BigDecimal#ROUND_HALF_EVEN ROUND_HALF_EVEN}) for formatting,
389      * and to parse only the integer part of an input string (see {@link
390      * #isParseIntegerOnly isParseIntegerOnly}).
391      *
392      * @param inLocale the locale for which a number format is needed
393      * @return a number format for integer values
394      * @since 1.4
395      */

396     public static NumberFormat JavaDoc getIntegerInstance(Locale JavaDoc inLocale) {
397         return getInstance(inLocale, INTEGERSTYLE);
398     }
399
400     /**
401      * Returns a currency format for the current default locale.
402      */

403     public final static NumberFormat JavaDoc getCurrencyInstance() {
404         return getInstance(Locale.getDefault(), CURRENCYSTYLE);
405     }
406
407     /**
408      * Returns a currency format for the specified locale.
409      */

410     public static NumberFormat JavaDoc getCurrencyInstance(Locale JavaDoc inLocale) {
411         return getInstance(inLocale, CURRENCYSTYLE);
412     }
413
414     /**
415      * Returns a percentage format for the current default locale.
416      */

417     public final static NumberFormat JavaDoc getPercentInstance() {
418         return getInstance(Locale.getDefault(), PERCENTSTYLE);
419     }
420
421     /**
422      * Returns a percentage format for the specified locale.
423      */

424     public static NumberFormat JavaDoc getPercentInstance(Locale JavaDoc inLocale) {
425         return getInstance(inLocale, PERCENTSTYLE);
426     }
427
428     /**
429      * Returns a scientific format for the current default locale.
430      */

431     /*public*/ final static NumberFormat JavaDoc getScientificInstance() {
432         return getInstance(Locale.getDefault(), SCIENTIFICSTYLE);
433     }
434
435     /**
436      * Returns a scientific format for the specified locale.
437      */

438     /*public*/ static NumberFormat JavaDoc getScientificInstance(Locale JavaDoc inLocale) {
439         return getInstance(inLocale, SCIENTIFICSTYLE);
440     }
441
442     /**
443      * Returns an array of all locales for which the
444      * <code>get*Instance</code> methods of this class can return
445      * localized instances.
446      * The array returned must contain at least a <code>Locale</code>
447      * instance equal to {@link java.util.Locale#US Locale.US}.
448      *
449      * @return An array of locales for which localized
450      * <code>NumberFormat</code> instances are available.
451      */

452     public static Locale JavaDoc[] getAvailableLocales() {
453         return LocaleData.getAvailableLocales("NumberPatterns");
454     }
455
456     /**
457      * Overrides hashCode
458      */

459     public int hashCode() {
460         return maximumIntegerDigits * 37 + maxFractionDigits;
461         // just enough fields for a reasonable distribution
462
}
463
464     /**
465      * Overrides equals
466      */

467     public boolean equals(Object JavaDoc obj) {
468         if (obj == null) {
469             return false;
470         }
471         if (this == obj) {
472             return true;
473         }
474         if (getClass() != obj.getClass()) {
475             return false;
476         }
477         NumberFormat JavaDoc other = (NumberFormat JavaDoc) obj;
478         return (maximumIntegerDigits == other.maximumIntegerDigits
479             && minimumIntegerDigits == other.minimumIntegerDigits
480             && maximumFractionDigits == other.maximumFractionDigits
481             && minimumFractionDigits == other.minimumFractionDigits
482             && groupingUsed == other.groupingUsed
483             && parseIntegerOnly == other.parseIntegerOnly);
484     }
485
486     /**
487      * Overrides Cloneable
488      */

489     public Object JavaDoc clone() {
490         NumberFormat JavaDoc other = (NumberFormat JavaDoc) super.clone();
491         return other;
492     }
493
494     /**
495      * Returns true if grouping is used in this format. For example, in the
496      * English locale, with grouping on, the number 1234567 might be formatted
497      * as "1,234,567". The grouping separator as well as the size of each group
498      * is locale dependant and is determined by sub-classes of NumberFormat.
499      * @see #setGroupingUsed
500      */

501     public boolean isGroupingUsed() {
502         return groupingUsed;
503     }
504
505     /**
506      * Set whether or not grouping will be used in this format.
507      * @see #isGroupingUsed
508      */

509     public void setGroupingUsed(boolean newValue) {
510         groupingUsed = newValue;
511     }
512
513     /**
514      * Returns the maximum number of digits allowed in the integer portion of a
515      * number.
516      * @see #setMaximumIntegerDigits
517      */

518     public int getMaximumIntegerDigits() {
519         return maximumIntegerDigits;
520     }
521
522     /**
523      * Sets the maximum number of digits allowed in the integer portion of a
524      * number. maximumIntegerDigits must be >= minimumIntegerDigits. If the
525      * new value for maximumIntegerDigits is less than the current value
526      * of minimumIntegerDigits, then minimumIntegerDigits will also be set to
527      * the new value.
528      * @param newValue the maximum number of integer digits to be shown; if
529      * less than zero, then zero is used. The concrete subclass may enforce an
530      * upper limit to this value appropriate to the numeric type being formatted.
531      * @see #getMaximumIntegerDigits
532      */

533     public void setMaximumIntegerDigits(int newValue) {
534         maximumIntegerDigits = Math.max(0,newValue);
535         if (minimumIntegerDigits > maximumIntegerDigits) {
536             minimumIntegerDigits = maximumIntegerDigits;
537         }
538     }
539
540     /**
541      * Returns the minimum number of digits allowed in the integer portion of a
542      * number.
543      * @see #setMinimumIntegerDigits
544      */

545     public int getMinimumIntegerDigits() {
546         return minimumIntegerDigits;
547     }
548
549     /**
550      * Sets the minimum number of digits allowed in the integer portion of a
551      * number. minimumIntegerDigits must be <= maximumIntegerDigits. If the
552      * new value for minimumIntegerDigits exceeds the current value
553      * of maximumIntegerDigits, then maximumIntegerDigits will also be set to
554      * the new value
555      * @param newValue the minimum number of integer digits to be shown; if
556      * less than zero, then zero is used. The concrete subclass may enforce an
557      * upper limit to this value appropriate to the numeric type being formatted.
558      * @see #getMinimumIntegerDigits
559      */

560     public void setMinimumIntegerDigits(int newValue) {
561         minimumIntegerDigits = Math.max(0,newValue);
562         if (minimumIntegerDigits > maximumIntegerDigits) {
563             maximumIntegerDigits = minimumIntegerDigits;
564         }
565     }
566
567     /**
568      * Returns the maximum number of digits allowed in the fraction portion of a
569      * number.
570      * @see #setMaximumFractionDigits
571      */

572     public int getMaximumFractionDigits() {
573         return maximumFractionDigits;
574     }
575
576     /**
577      * Sets the maximum number of digits allowed in the fraction portion of a
578      * number. maximumFractionDigits must be >= minimumFractionDigits. If the
579      * new value for maximumFractionDigits is less than the current value
580      * of minimumFractionDigits, then minimumFractionDigits will also be set to
581      * the new value.
582      * @param newValue the maximum number of fraction digits to be shown; if
583      * less than zero, then zero is used. The concrete subclass may enforce an
584      * upper limit to this value appropriate to the numeric type being formatted.
585      * @see #getMaximumFractionDigits
586      */

587     public void setMaximumFractionDigits(int newValue) {
588         maximumFractionDigits = Math.max(0,newValue);
589         if (maximumFractionDigits < minimumFractionDigits) {
590             minimumFractionDigits = maximumFractionDigits;
591         }
592     }
593
594     /**
595      * Returns the minimum number of digits allowed in the fraction portion of a
596      * number.
597      * @see #setMinimumFractionDigits
598      */

599     public int getMinimumFractionDigits() {
600         return minimumFractionDigits;
601     }
602
603     /**
604      * Sets the minimum number of digits allowed in the fraction portion of a
605      * number. minimumFractionDigits must be <= maximumFractionDigits. If the
606      * new value for minimumFractionDigits exceeds the current value
607      * of maximumFractionDigits, then maximumIntegerDigits will also be set to
608      * the new value
609      * @param newValue the minimum number of fraction digits to be shown; if
610      * less than zero, then zero is used. The concrete subclass may enforce an
611      * upper limit to this value appropriate to the numeric type being formatted.
612      * @see #getMinimumFractionDigits
613      */

614     public void setMinimumFractionDigits(int newValue) {
615         minimumFractionDigits = Math.max(0,newValue);
616         if (maximumFractionDigits < minimumFractionDigits) {
617             maximumFractionDigits = minimumFractionDigits;
618         }
619     }
620     
621     /**
622      * Gets the currency used by this number format when formatting
623      * currency values. The initial value is derived in a locale dependent
624      * way. The returned value may be null if no valid
625      * currency could be determined and no currency has been set using
626      * {@link #setCurrency(java.util.Currency) setCurrency}.
627      * <p>
628      * The default implementation throws
629      * <code>UnsupportedOperationException</code>.
630      *
631      * @return the currency used by this number format, or <code>null</code>
632      * @exception UnsupportedOperationException if the number format class
633      * doesn't implement currency formatting
634      * @since 1.4
635      */

636     public Currency JavaDoc getCurrency() {
637         throw new UnsupportedOperationException JavaDoc();
638     }
639     
640     /**
641      * Sets the currency used by this number format when formatting
642      * currency values. This does not update the minimum or maximum
643      * number of fraction digits used by the number format.
644      * <p>
645      * The default implementation throws
646      * <code>UnsupportedOperationException</code>.
647      *
648      * @param currency the new currency to be used by this number format
649      * @exception UnsupportedOperationException if the number format class
650      * doesn't implement currency formatting
651      * @exception NullPointerException if <code>currency</code> is null
652      * @since 1.4
653      */

654     public void setCurrency(Currency JavaDoc currency) {
655         throw new UnsupportedOperationException JavaDoc();
656     }
657
658     // =======================privates===============================
659

660     private static NumberFormat JavaDoc getInstance(Locale JavaDoc desiredLocale,
661                                            int choice) {
662         /* try the cache first */
663         String JavaDoc[] numberPatterns = (String JavaDoc[])cachedLocaleData.get(desiredLocale);
664         if (numberPatterns == null) { /* cache miss */
665             ResourceBundle JavaDoc resource = LocaleData.getLocaleElements(desiredLocale);
666             numberPatterns = resource.getStringArray("NumberPatterns");
667             /* update cache */
668             cachedLocaleData.put(desiredLocale, numberPatterns);
669         }
670         
671         DecimalFormatSymbols JavaDoc symbols = new DecimalFormatSymbols JavaDoc(desiredLocale);
672         int entry = (choice == INTEGERSTYLE) ? NUMBERSTYLE : choice;
673         DecimalFormat JavaDoc format = new DecimalFormat JavaDoc(numberPatterns[entry], symbols);
674         
675         if (choice == INTEGERSTYLE) {
676             format.setMaximumFractionDigits(0);
677             format.setDecimalSeparatorAlwaysShown(false);
678             format.setParseIntegerOnly(true);
679         } else if (choice == CURRENCYSTYLE) {
680             format.adjustForCurrencyDefaultFractionDigits();
681         }
682
683         return format;
684     }
685
686     /**
687      * First, read in the default serializable data.
688      *
689      * Then, if <code>serialVersionOnStream</code> is less than 1, indicating that
690      * the stream was written by JDK 1.1,
691      * set the <code>int</code> fields such as <code>maximumIntegerDigits</code>
692      * to be equal to the <code>byte</code> fields such as <code>maxIntegerDigits</code>,
693      * since the <code>int</code> fields were not present in JDK 1.1.
694      * Finally, set serialVersionOnStream back to the maximum allowed value so that
695      * default serialization will work properly if this object is streamed out again.
696      *
697      * <p>If <code>minimumIntegerDigits</code> is greater than
698      * <code>maximumIntegerDigits</code> or <code>minimumFractionDigits</code>
699      * is greater than <code>maximumFractionDigits</code>, then the stream data
700      * is invalid and this method throws an <code>InvalidObjectException</code>.
701      * In addition, if any of these values is negative, then this method throws
702      * an <code>InvalidObjectException</code>.
703      *
704      * @since 1.2
705      */

706     private void readObject(ObjectInputStream JavaDoc stream)
707          throws IOException JavaDoc, ClassNotFoundException JavaDoc
708     {
709         stream.defaultReadObject();
710         if (serialVersionOnStream < 1) {
711             // Didn't have additional int fields, reassign to use them.
712
maximumIntegerDigits = maxIntegerDigits;
713             minimumIntegerDigits = minIntegerDigits;
714             maximumFractionDigits = maxFractionDigits;
715             minimumFractionDigits = minFractionDigits;
716         }
717         if (minimumIntegerDigits > maximumIntegerDigits ||
718             minimumFractionDigits > maximumFractionDigits ||
719             minimumIntegerDigits < 0 || minimumFractionDigits < 0) {
720             throw new InvalidObjectException JavaDoc("Digit count range invalid");
721         }
722         serialVersionOnStream = currentSerialVersion;
723     }
724
725     /**
726      * Write out the default serializable data, after first setting
727      * the <code>byte</code> fields such as <code>maxIntegerDigits</code> to be
728      * equal to the <code>int</code> fields such as <code>maximumIntegerDigits</code>
729      * (or to <code>Byte.MAX_VALUE</code>, whichever is smaller), for compatibility
730      * with the JDK 1.1 version of the stream format.
731      *
732      * @since 1.2
733      */

734     private void writeObject(ObjectOutputStream JavaDoc stream)
735          throws IOException JavaDoc
736     {
737         maxIntegerDigits = (maximumIntegerDigits > Byte.MAX_VALUE) ?
738                            Byte.MAX_VALUE : (byte)maximumIntegerDigits;
739         minIntegerDigits = (minimumIntegerDigits > Byte.MAX_VALUE) ?
740                            Byte.MAX_VALUE : (byte)minimumIntegerDigits;
741         maxFractionDigits = (maximumFractionDigits > Byte.MAX_VALUE) ?
742                             Byte.MAX_VALUE : (byte)maximumFractionDigits;
743         minFractionDigits = (minimumFractionDigits > Byte.MAX_VALUE) ?
744                             Byte.MAX_VALUE : (byte)minimumFractionDigits;
745         stream.defaultWriteObject();
746     }
747
748     /**
749      * Cache to hold the NumberPatterns of a Locale.
750      */

751     private static final Hashtable JavaDoc cachedLocaleData = new Hashtable JavaDoc(3);
752
753     // Constants used by factory methods to specify a style of format.
754
private static final int NUMBERSTYLE = 0;
755     private static final int CURRENCYSTYLE = 1;
756     private static final int PERCENTSTYLE = 2;
757     private static final int SCIENTIFICSTYLE = 3;
758     private static final int INTEGERSTYLE = 4;
759
760     /**
761      * True if the the grouping (i.e. thousands) separator is used when
762      * formatting and parsing numbers.
763      *
764      * @serial
765      * @see #isGroupingUsed
766      */

767     private boolean groupingUsed = true;
768
769     /**
770      * The maximum number of digits allowed in the integer portion of a
771      * number. <code>maxIntegerDigits</code> must be greater than or equal to
772      * <code>minIntegerDigits</code>.
773      * <p>
774      * <strong>Note:</strong> This field exists only for serialization
775      * compatibility with JDK 1.1. In Java platform 2 v1.2 and higher, the new
776      * <code>int</code> field <code>maximumIntegerDigits</code> is used instead.
777      * When writing to a stream, <code>maxIntegerDigits</code> is set to
778      * <code>maximumIntegerDigits</code> or <code>Byte.MAX_VALUE</code>,
779      * whichever is smaller. When reading from a stream, this field is used
780      * only if <code>serialVersionOnStream</code> is less than 1.
781      *
782      * @serial
783      * @see #getMaximumIntegerDigits
784      */

785     private byte maxIntegerDigits = 40;
786
787     /**
788      * The minimum number of digits allowed in the integer portion of a
789      * number. <code>minimumIntegerDigits</code> must be less than or equal to
790      * <code>maximumIntegerDigits</code>.
791      * <p>
792      * <strong>Note:</strong> This field exists only for serialization
793      * compatibility with JDK 1.1. In Java platform 2 v1.2 and higher, the new
794      * <code>int</code> field <code>minimumIntegerDigits</code> is used instead.
795      * When writing to a stream, <code>minIntegerDigits</code> is set to
796      * <code>minimumIntegerDigits</code> or <code>Byte.MAX_VALUE</code>,
797      * whichever is smaller. When reading from a stream, this field is used
798      * only if <code>serialVersionOnStream</code> is less than 1.
799      *
800      * @serial
801      * @see #getMinimumIntegerDigits
802      */

803     private byte minIntegerDigits = 1;
804
805     /**
806      * The maximum number of digits allowed in the fractional portion of a
807      * number. <code>maximumFractionDigits</code> must be greater than or equal to
808      * <code>minimumFractionDigits</code>.
809      * <p>
810      * <strong>Note:</strong> This field exists only for serialization
811      * compatibility with JDK 1.1. In Java platform 2 v1.2 and higher, the new
812      * <code>int</code> field <code>maximumFractionDigits</code> is used instead.
813      * When writing to a stream, <code>maxFractionDigits</code> is set to
814      * <code>maximumFractionDigits</code> or <code>Byte.MAX_VALUE</code>,
815      * whichever is smaller. When reading from a stream, this field is used
816      * only if <code>serialVersionOnStream</code> is less than 1.
817      *
818      * @serial
819      * @see #getMaximumFractionDigits
820      */

821     private byte maxFractionDigits = 3; // invariant, >= minFractionDigits
822

823     /**
824      * The minimum number of digits allowed in the fractional portion of a
825      * number. <code>minimumFractionDigits</code> must be less than or equal to
826      * <code>maximumFractionDigits</code>.
827      * <p>
828      * <strong>Note:</strong> This field exists only for serialization
829      * compatibility with JDK 1.1. In Java platform 2 v1.2 and higher, the new
830      * <code>int</code> field <code>minimumFractionDigits</code> is used instead.
831      * When writing to a stream, <code>minFractionDigits</code> is set to
832      * <code>minimumFractionDigits</code> or <code>Byte.MAX_VALUE</code>,
833      * whichever is smaller. When reading from a stream, this field is used
834      * only if <code>serialVersionOnStream</code> is less than 1.
835      *
836      * @serial
837      * @see #getMinimumFractionDigits
838      */

839     private byte minFractionDigits = 0;
840
841     /**
842      * True if this format will parse numbers as integers only.
843      *
844      * @serial
845      * @see #isParseIntegerOnly
846      */

847     private boolean parseIntegerOnly = false;
848
849     // new fields for 1.2. byte is too small for integer digits.
850

851     /**
852      * The maximum number of digits allowed in the integer portion of a
853      * number. <code>maximumIntegerDigits</code> must be greater than or equal to
854      * <code>minimumIntegerDigits</code>.
855      *
856      * @serial
857      * @since 1.2
858      * @see #getMaximumIntegerDigits
859      */

860     private int maximumIntegerDigits = 40;
861
862     /**
863      * The minimum number of digits allowed in the integer portion of a
864      * number. <code>minimumIntegerDigits</code> must be less than or equal to
865      * <code>maximumIntegerDigits</code>.
866      *
867      * @serial
868      * @since 1.2
869      * @see #getMinimumIntegerDigits
870      */

871     private int minimumIntegerDigits = 1;
872
873     /**
874      * The maximum number of digits allowed in the fractional portion of a
875      * number. <code>maximumFractionDigits</code> must be greater than or equal to
876      * <code>minimumFractionDigits</code>.
877      *
878      * @serial
879      * @since 1.2
880      * @see #getMaximumFractionDigits
881      */

882     private int maximumFractionDigits = 3; // invariant, >= minFractionDigits
883

884     /**
885      * The minimum number of digits allowed in the fractional portion of a
886      * number. <code>minimumFractionDigits</code> must be less than or equal to
887      * <code>maximumFractionDigits</code>.
888      *
889      * @serial
890      * @since 1.2
891      * @see #getMinimumFractionDigits
892      */

893     private int minimumFractionDigits = 0;
894
895     static final int currentSerialVersion = 1;
896
897     /**
898      * Describes the version of <code>NumberFormat</code> present on the stream.
899      * Possible values are:
900      * <ul>
901      * <li><b>0</b> (or uninitialized): the JDK 1.1 version of the stream format.
902      * In this version, the <code>int</code> fields such as
903      * <code>maximumIntegerDigits</code> were not present, and the <code>byte</code>
904      * fields such as <code>maxIntegerDigits</code> are used instead.
905      *
906      * <li><b>1</b>: the 1.2 version of the stream format. The values of the
907      * <code>byte</code> fields such as <code>maxIntegerDigits</code> are ignored,
908      * and the <code>int</code> fields such as <code>maximumIntegerDigits</code>
909      * are used instead.
910      * </ul>
911      * When streaming out a <code>NumberFormat</code>, the most recent format
912      * (corresponding to the highest allowable <code>serialVersionOnStream</code>)
913      * is always written.
914      *
915      * @serial
916      * @since 1.2
917      */

918     private int serialVersionOnStream = currentSerialVersion;
919
920     // Removed "implements Cloneable" clause. Needs to update serialization
921
// ID for backward compatibility.
922
static final long serialVersionUID = -2308460125733713944L;
923
924
925     //
926
// class for AttributedCharacterIterator attributes
927
//
928
/**
929      * Defines constants that are used as attribute keys in the
930      * <code>AttributedCharacterIterator</code> returned
931      * from <code>NumberFormat.formatToCharacterIterator</code> and as
932      * field identifiers in <code>FieldPosition</code>.
933      *
934      * @since 1.4
935      */

936     public static class Field extends Format.Field JavaDoc {
937
938         // Proclaim serial compatibility with 1.4 FCS
939
private static final long serialVersionUID = 7494728892700160890L;
940
941         // table of all instances in this class, used by readResolve
942
private static final Map JavaDoc instanceMap = new HashMap JavaDoc(11);
943
944         /**
945          * Creates a Field instance with the specified
946          * name.
947          *
948          * @param name Name of the attribute
949          */

950         protected Field(String JavaDoc name) {
951             super(name);
952             if (this.getClass() == NumberFormat.Field JavaDoc.class) {
953                 instanceMap.put(name, this);
954             }
955         }
956
957         /**
958          * Resolves instances being deserialized to the predefined constants.
959          *
960          * @throws InvalidObjectException if the constant could not be resolved.
961          * @return resolved NumberFormat.Field constant
962          */

963         protected Object JavaDoc readResolve() throws InvalidObjectException JavaDoc {
964             if (this.getClass() != NumberFormat.Field JavaDoc.class) {
965                 throw new InvalidObjectException JavaDoc("subclass didn't correctly implement readResolve");
966             }
967
968             Object JavaDoc instance = instanceMap.get(getName());
969             if (instance != null) {
970                 return instance;
971             } else {
972                 throw new InvalidObjectException JavaDoc("unknown attribute name");
973             }
974         }
975
976         /**
977          * Constant identifying the integer field.
978          */

979         public static final Field INTEGER = new Field("integer");
980
981         /**
982          * Constant identifying the fraction field.
983          */

984         public static final Field FRACTION = new Field("fraction");
985
986         /**
987          * Constant identifying the exponent field.
988          */

989         public static final Field EXPONENT = new Field("exponent");
990
991         /**
992          * Constant identifying the decimal separator field.
993          */

994         public static final Field DECIMAL_SEPARATOR =
995                             new Field("decimal separator");
996
997         /**
998          * Constant identifying the sign field.
999          */

1000        public static final Field SIGN = new Field("sign");
1001
1002        /**
1003         * Constant identifying the grouping separator field.
1004         */

1005        public static final Field GROUPING_SEPARATOR =
1006                            new Field("grouping separator");
1007
1008        /**
1009         * Constant identifying the exponent symbol field.
1010         */

1011        public static final Field EXPONENT_SYMBOL = new
1012                            Field("exponent symbol");
1013
1014        /**
1015         * Constant identifying the percent field.
1016         */

1017        public static final Field PERCENT = new Field("percent");
1018
1019        /**
1020         * Constant identifying the permille field.
1021         */

1022        public static final Field PERMILLE = new Field("per mille");
1023
1024        /**
1025         * Constant identifying the currency field.
1026         */

1027        public static final Field CURRENCY = new Field("currency");
1028
1029        /**
1030         * Constant identifying the exponent sign field.
1031         */

1032        public static final Field EXPONENT_SIGN = new Field("exponent sign");
1033    }
1034}
1035
Popular Tags