KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > java > text > DecimalFormat


1 /*
2  * @(#)DecimalFormat.java 1.79 04/06/28
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.math.BigDecimal JavaDoc;
27 import java.math.BigInteger JavaDoc;
28 import java.util.ArrayList JavaDoc;
29 import java.util.Currency JavaDoc;
30 import java.util.Hashtable JavaDoc;
31 import java.util.Locale JavaDoc;
32 import java.util.ResourceBundle JavaDoc;
33 import sun.text.resources.LocaleData;
34
35 /**
36  * <code>DecimalFormat</code> is a concrete subclass of
37  * <code>NumberFormat</code> that formats decimal numbers. It has a variety of
38  * features designed to make it possible to parse and format numbers in any
39  * locale, including support for Western, Arabic, and Indic digits. It also
40  * supports different kinds of numbers, including integers (123), fixed-point
41  * numbers (123.4), scientific notation (1.23E4), percentages (12%), and
42  * currency amounts ($123). All of these can be localized.
43  *
44  * <p>To obtain a <code>NumberFormat</code> for a specific locale, including the
45  * default locale, call one of <code>NumberFormat</code>'s factory methods, such
46  * as <code>getInstance()</code>. In general, do not call the
47  * <code>DecimalFormat</code> constructors directly, since the
48  * <code>NumberFormat</code> factory methods may return subclasses other than
49  * <code>DecimalFormat</code>. If you need to customize the format object, do
50  * something like this:
51  *
52  * <blockquote><pre>
53  * NumberFormat f = NumberFormat.getInstance(loc);
54  * if (f instanceof DecimalFormat) {
55  * ((DecimalFormat) f).setDecimalSeparatorAlwaysShown(true);
56  * }
57  * </pre></blockquote>
58  *
59  * <p>A <code>DecimalFormat</code> comprises a <em>pattern</em> and a set of
60  * <em>symbols</em>. The pattern may be set directly using
61  * <code>applyPattern()</code>, or indirectly using the API methods. The
62  * symbols are stored in a <code>DecimalFormatSymbols</code> object. When using
63  * the <code>NumberFormat</code> factory methods, the pattern and symbols are
64  * read from localized <code>ResourceBundle</code>s.
65  *
66  * <h4>Patterns</h4>
67  *
68  * <code>DecimalFormat</code> patterns have the following syntax:
69  * <blockquote><pre>
70  * <i>Pattern:</i>
71  * <i>PositivePattern</i>
72  * <i>PositivePattern</i> ; <i>NegativePattern</i>
73  * <i>PositivePattern:</i>
74  * <i>Prefix<sub>opt</sub></i> <i>Number</i> <i>Suffix<sub>opt</sub></i>
75  * <i>NegativePattern:</i>
76  * <i>Prefix<sub>opt</sub></i> <i>Number</i> <i>Suffix<sub>opt</sub></i>
77  * <i>Prefix:</i>
78  * any Unicode characters except &#92;uFFFE, &#92;uFFFF, and special characters
79  * <i>Suffix:</i>
80  * any Unicode characters except &#92;uFFFE, &#92;uFFFF, and special characters
81  * <i>Number:</i>
82  * <i>Integer</i> <i>Exponent<sub>opt</sub></i>
83  * <i>Integer</i> . <i>Fraction</i> <i>Exponent<sub>opt</sub></i>
84  * <i>Integer:</i>
85  * <i>MinimumInteger</i>
86  * #
87  * # <i>Integer</i>
88  * # , <i>Integer</i>
89  * <i>MinimumInteger:</i>
90  * 0
91  * 0 <i>MinimumInteger</i>
92  * 0 , <i>MinimumInteger</i>
93  * <i>Fraction:</i>
94  * <i>MinimumFraction<sub>opt</sub></i> <i>OptionalFraction<sub>opt</sub></i>
95  * <i>MinimumFraction:</i>
96  * 0 <i>MinimumFraction<sub>opt</sub></i>
97  * <i>OptionalFraction:</i>
98  * # <i>OptionalFraction<sub>opt</sub></i>
99  * <i>Exponent:</i>
100  * E <i>MinimumExponent</i>
101  * <i>MinimumExponent:</i>
102  * 0 <i>MinimumExponent<sub>opt</sub></i>
103  * </pre></blockquote>
104  *
105  * <p>A <code>DecimalFormat</code> pattern contains a positive and negative
106  * subpattern, for example, <code>"#,##0.00;(#,##0.00)"</code>. Each
107  * subpattern has a prefix, numeric part, and suffix. The negative subpattern
108  * is optional; if absent, then the positive subpattern prefixed with the
109  * localized minus sign (<code>'-'</code> in most locales) is used as the
110  * negative subpattern. That is, <code>"0.00"</code> alone is equivalent to
111  * <code>"0.00;-0.00"</code>. If there is an explicit negative subpattern, it
112  * serves only to specify the negative prefix and suffix; the number of digits,
113  * minimal digits, and other characteristics are all the same as the positive
114  * pattern. That means that <code>"#,##0.0#;(#)"</code> produces precisely
115  * the same behavior as <code>"#,##0.0#;(#,##0.0#)"</code>.
116  *
117  * <p>The prefixes, suffixes, and various symbols used for infinity, digits,
118  * thousands separators, decimal separators, etc. may be set to arbitrary
119  * values, and they will appear properly during formatting. However, care must
120  * be taken that the symbols and strings do not conflict, or parsing will be
121  * unreliable. For example, either the positive and negative prefixes or the
122  * suffixes must be distinct for <code>DecimalFormat.parse()</code> to be able
123  * to distinguish positive from negative values. (If they are identical, then
124  * <code>DecimalFormat</code> will behave as if no negative subpattern was
125  * specified.) Another example is that the decimal separator and thousands
126  * separator should be distinct characters, or parsing will be impossible.
127  *
128  * <p>The grouping separator is commonly used for thousands, but in some
129  * countries it separates ten-thousands. The grouping size is a constant number
130  * of digits between the grouping characters, such as 3 for 100,000,000 or 4 for
131  * 1,0000,0000. If you supply a pattern with multiple grouping characters, the
132  * interval between the last one and the end of the integer is the one that is
133  * used. So <code>"#,##,###,####"</code> == <code>"######,####"</code> ==
134  * <code>"##,####,####"</code>.
135  *
136  * <h4>Special Pattern Characters</h4>
137  *
138  * <p>Many characters in a pattern are taken literally; they are matched during
139  * parsing and output unchanged during formatting. Special characters, on the
140  * other hand, stand for other characters, strings, or classes of characters.
141  * They must be quoted, unless noted otherwise, if they are to appear in the
142  * prefix or suffix as literals.
143  *
144  * <p>The characters listed here are used in non-localized patterns. Localized
145  * patterns use the corresponding characters taken from this formatter's
146  * <code>DecimalFormatSymbols</code> object instead, and these characters lose
147  * their special status. Two exceptions are the currency sign and quote, which
148  * are not localized.
149  *
150  * <blockquote>
151  * <table border=0 cellspacing=3 cellpadding=0 summary="Chart showing symbol,
152  * location, localized, and meaning.">
153  * <tr bgcolor="#ccccff">
154  * <th align=left>Symbol
155  * <th align=left>Location
156  * <th align=left>Localized?
157  * <th align=left>Meaning
158  * <tr valign=top>
159  * <td><code>0</code>
160  * <td>Number
161  * <td>Yes
162  * <td>Digit
163  * <tr valign=top bgcolor="#eeeeff">
164  * <td><code>#</code>
165  * <td>Number
166  * <td>Yes
167  * <td>Digit, zero shows as absent
168  * <tr valign=top>
169  * <td><code>.</code>
170  * <td>Number
171  * <td>Yes
172  * <td>Decimal separator or monetary decimal separator
173  * <tr valign=top bgcolor="#eeeeff">
174  * <td><code>-</code>
175  * <td>Number
176  * <td>Yes
177  * <td>Minus sign
178  * <tr valign=top>
179  * <td><code>,</code>
180  * <td>Number
181  * <td>Yes
182  * <td>Grouping separator
183  * <tr valign=top bgcolor="#eeeeff">
184  * <td><code>E</code>
185  * <td>Number
186  * <td>Yes
187  * <td>Separates mantissa and exponent in scientific notation.
188  * <em>Need not be quoted in prefix or suffix.</em>
189  * <tr valign=top>
190  * <td><code>;</code>
191  * <td>Subpattern boundary
192  * <td>Yes
193  * <td>Separates positive and negative subpatterns
194  * <tr valign=top bgcolor="#eeeeff">
195  * <td><code>%</code>
196  * <td>Prefix or suffix
197  * <td>Yes
198  * <td>Multiply by 100 and show as percentage
199  * <tr valign=top>
200  * <td><code>&#92;u2030</code>
201  * <td>Prefix or suffix
202  * <td>Yes
203  * <td>Multiply by 1000 and show as per mille value
204  * <tr valign=top bgcolor="#eeeeff">
205  * <td><code>&#164;</code> (<code>&#92;u00A4</code>)
206  * <td>Prefix or suffix
207  * <td>No
208  * <td>Currency sign, replaced by currency symbol. If
209  * doubled, replaced by international currency symbol.
210  * If present in a pattern, the monetary decimal separator
211  * is used instead of the decimal separator.
212  * <tr valign=top>
213  * <td><code>'</code>
214  * <td>Prefix or suffix
215  * <td>No
216  * <td>Used to quote special characters in a prefix or suffix,
217  * for example, <code>"'#'#"</code> formats 123 to
218  * <code>"#123"</code>. To create a single quote
219  * itself, use two in a row: <code>"# o''clock"</code>.
220  * </table>
221  * </blockquote>
222  *
223  * <h4>Scientific Notation</h4>
224  *
225  * <p>Numbers in scientific notation are expressed as the product of a mantissa
226  * and a power of ten, for example, 1234 can be expressed as 1.234 x 10^3. The
227  * mantissa is often in the range 1.0 <= x < 10.0, but it need not be.
228  * <code>DecimalFormat</code> can be instructed to format and parse scientific
229  * notation <em>only via a pattern</em>; there is currently no factory method
230  * that creates a scientific notation format. In a pattern, the exponent
231  * character immediately followed by one or more digit characters indicates
232  * scientific notation. Example: <code>"0.###E0"</code> formats the number
233  * 1234 as <code>"1.234E3"</code>.
234  *
235  * <ul>
236  * <li>The number of digit characters after the exponent character gives the
237  * minimum exponent digit count. There is no maximum. Negative exponents are
238  * formatted using the localized minus sign, <em>not</em> the prefix and suffix
239  * from the pattern. This allows patterns such as <code>"0.###E0 m/s"</code>.
240  *
241  * <li>The minimum and maximum number of integer digits are interpreted
242  * together:
243  *
244  * <ul>
245  * <li>If the maximum number of integer digits is greater than their minimum number
246  * and greater than 1, it forces the exponent to be a multiple of the maximum
247  * number of integer digits, and the minimum number of integer digits to be
248  * interpreted as 1. The most common use of this is to generate
249  * <em>engineering notation</em>, in which the exponent is a multiple of three,
250  * e.g., <code>"##0.#####E0"</code>. Using this pattern, the number 12345
251  * formats to <code>"12.345E3"</code>, and 123456 formats to
252  * <code>"123.456E3"</code>.
253  *
254  * <li>Otherwise, the minimum number of integer digits is achieved by adjusting the
255  * exponent. Example: 0.00123 formatted with <code>"00.###E0"</code> yields
256  * <code>"12.3E-4"</code>.
257  * </ul>
258  *
259  * <li>The number of significant digits in the mantissa is the sum of the
260  * <em>minimum integer</em> and <em>maximum fraction</em> digits, and is
261  * unaffected by the maximum integer digits. For example, 12345 formatted with
262  * <code>"##0.##E0"</code> is <code>"12.3E3"</code>. To show all digits, set
263  * the significant digits count to zero. The number of significant digits
264  * does not affect parsing.
265  *
266  * <li>Exponential patterns may not contain grouping separators.
267  * </ul>
268  *
269  * <h4>Rounding</h4>
270  *
271  * <code>DecimalFormat</code> uses half-even rounding (see
272  * {@link java.math.BigDecimal#ROUND_HALF_EVEN ROUND_HALF_EVEN}) for
273  * formatting.
274  *
275  * <h4>Digits</h4>
276  *
277  * For formatting, <code>DecimalFormat</code> uses the ten consecutive
278  * characters starting with the localized zero digit defined in the
279  * <code>DecimalFormatSymbols</code> object as digits. For parsing, these
280  * digits as well as all Unicode decimal digits, as defined by
281  * {@link Character#digit Character.digit}, are recognized.
282  *
283  * <h4>Special Values</h4>
284  *
285  * <p><code>NaN</code> is formatted as a single character, typically
286  * <code>&#92;uFFFD</code>. This character is determined by the
287  * <code>DecimalFormatSymbols</code> object. This is the only value for which
288  * the prefixes and suffixes are not used.
289  *
290  * <p>Infinity is formatted as a single character, typically
291  * <code>&#92;u221E</code>, with the positive or negative prefixes and suffixes
292  * applied. The infinity character is determined by the
293  * <code>DecimalFormatSymbols</code> object.
294  *
295  * <p>Negative zero (<code>"-0"</code>) parses to
296  * <ul>
297  * <li><code>BigDecimal(0)</code> if <code>isParseBigDecimal()</code> is
298  * true,
299  * <li><code>Long(0)</code> if <code>isParseBigDecimal()</code> is false
300  * and <code>isParseIntegerOnly()</code> is true,
301  * <li><code>Double(-0.0)</code> if both <code>isParseBigDecimal()</code>
302  * and <code>isParseIntegerOnly()</code> are false.
303  * </ul>
304  *
305  * <h4><a name="synchronization">Synchronization</a></h4>
306  *
307  * <p>
308  * Decimal formats are generally not synchronized.
309  * It is recommended to create separate format instances for each thread.
310  * If multiple threads access a format concurrently, it must be synchronized
311  * externally.
312  *
313  * <h4>Example</h4>
314  *
315  * <blockquote><pre>
316  * <strong>// Print out a number using the localized number, integer, currency,
317  * // and percent format for each locale</strong>
318  * Locale[] locales = NumberFormat.getAvailableLocales();
319  * double myNumber = -1234.56;
320  * NumberFormat form;
321  * for (int j=0; j<4; ++j) {
322  * System.out.println("FORMAT");
323  * for (int i = 0; i < locales.length; ++i) {
324  * if (locales[i].getCountry().length() == 0) {
325  * continue; // Skip language-only locales
326  * }
327  * System.out.print(locales[i].getDisplayName());
328  * switch (j) {
329  * case 0:
330  * form = NumberFormat.getInstance(locales[i]); break;
331  * case 1:
332  * form = NumberFormat.getIntegerInstance(locales[i]); break;
333  * case 2:
334  * form = NumberFormat.getCurrencyInstance(locales[i]); break;
335  * default:
336  * form = NumberFormat.getPercentInstance(locales[i]); break;
337  * }
338  * if (form instanceof DecimalFormat) {
339  * System.out.print(": " + ((DecimalFormat) form).toPattern());
340  * }
341  * System.out.print(" -> " + form.format(myNumber));
342  * try {
343  * System.out.println(" -> " + form.parse(form.format(myNumber)));
344  * } catch (ParseException e) {}
345  * }
346  * }
347  * </pre></blockquote>
348  *
349  * @see <a HREF="http://java.sun.com/docs/books/tutorial/i18n/format/decimalFormat.html">Java Tutorial</a>
350  * @see NumberFormat
351  * @see DecimalFormatSymbols
352  * @see ParsePosition
353  * @version 1.79 06/28/04
354  * @author Mark Davis
355  * @author Alan Liu
356  */

357 public class DecimalFormat extends NumberFormat JavaDoc {
358
359     /**
360      * Creates a DecimalFormat using the default pattern and symbols
361      * for the default locale. This is a convenient way to obtain a
362      * DecimalFormat when internationalization is not the main concern.
363      * <p>
364      * To obtain standard formats for a given locale, use the factory methods
365      * on NumberFormat such as getNumberInstance. These factories will
366      * return the most appropriate sub-class of NumberFormat for a given
367      * locale.
368      *
369      * @see java.text.NumberFormat#getInstance
370      * @see java.text.NumberFormat#getNumberInstance
371      * @see java.text.NumberFormat#getCurrencyInstance
372      * @see java.text.NumberFormat#getPercentInstance
373      */

374     public DecimalFormat() {
375         Locale JavaDoc def = Locale.getDefault();
376         // try to get the pattern from the cache
377
String JavaDoc pattern = (String JavaDoc) cachedLocaleData.get(def);
378         if (pattern == null) { /* cache miss */
379             // Get the pattern for the default locale.
380
ResourceBundle JavaDoc rb = LocaleData.getLocaleElements(def);
381             String JavaDoc[] all = rb.getStringArray("NumberPatterns");
382             pattern = all[0];
383             /* update cache */
384             cachedLocaleData.put(def, pattern);
385         }
386
387         // Always applyPattern after the symbols are set
388
this.symbols = new DecimalFormatSymbols JavaDoc(def);
389         applyPattern(pattern, false);
390     }
391
392
393     /**
394      * Creates a DecimalFormat using the given pattern and the symbols
395      * for the default locale. This is a convenient way to obtain a
396      * DecimalFormat when internationalization is not the main concern.
397      * <p>
398      * To obtain standard formats for a given locale, use the factory methods
399      * on NumberFormat such as getNumberInstance. These factories will
400      * return the most appropriate sub-class of NumberFormat for a given
401      * locale.
402      *
403      * @param pattern A non-localized pattern string.
404      * @exception NullPointerException if <code>pattern</code> is null
405      * @exception IllegalArgumentException if the given pattern is invalid.
406      * @see java.text.NumberFormat#getInstance
407      * @see java.text.NumberFormat#getNumberInstance
408      * @see java.text.NumberFormat#getCurrencyInstance
409      * @see java.text.NumberFormat#getPercentInstance
410      */

411     public DecimalFormat(String JavaDoc pattern) {
412         // Always applyPattern after the symbols are set
413
this.symbols = new DecimalFormatSymbols JavaDoc(Locale.getDefault());
414         applyPattern(pattern, false);
415     }
416
417
418     /**
419      * Creates a DecimalFormat using the given pattern and symbols.
420      * Use this constructor when you need to completely customize the
421      * behavior of the format.
422      * <p>
423      * To obtain standard formats for a given
424      * locale, use the factory methods on NumberFormat such as
425      * getInstance or getCurrencyInstance. If you need only minor adjustments
426      * to a standard format, you can modify the format returned by
427      * a NumberFormat factory method.
428      *
429      * @param pattern a non-localized pattern string
430      * @param symbols the set of symbols to be used
431      * @exception NullPointerException if any of the given arguments is null
432      * @exception IllegalArgumentException if the given pattern is invalid
433      * @see java.text.NumberFormat#getInstance
434      * @see java.text.NumberFormat#getNumberInstance
435      * @see java.text.NumberFormat#getCurrencyInstance
436      * @see java.text.NumberFormat#getPercentInstance
437      * @see java.text.DecimalFormatSymbols
438      */

439     public DecimalFormat (String JavaDoc pattern, DecimalFormatSymbols JavaDoc symbols) {
440         // Always applyPattern after the symbols are set
441
this.symbols = (DecimalFormatSymbols JavaDoc)symbols.clone();
442         applyPattern(pattern, false);
443     }
444
445
446     // Overrides
447
/**
448      * Formats a number and appends the resulting text to the given string
449      * buffer.
450      * The number can be of any subclass of {@link java.lang.Number}.
451      * <p>
452      * This implementation uses the maximum precision permitted.
453      * @param number the number to format
454      * @param toAppendTo the <code>StringBuffer</code> to which the formatted
455      * text is to be appended
456      * @param pos On input: an alignment field, if desired.
457      * On output: the offsets of the alignment field.
458      * @return the value passed in as <code>toAppendTo</code>
459      * @exception IllegalArgumentException if <code>number</code> is
460      * null or not an instance of <code>Number</code>.
461      * @exception NullPointerException if <code>toAppendTo</code> or
462      * <code>pos</code> is null
463      * @see java.text.FieldPosition
464      */

465     public final StringBuffer JavaDoc format(Object JavaDoc number,
466                                      StringBuffer JavaDoc toAppendTo,
467                                      FieldPosition JavaDoc pos) {
468         if (number instanceof Long JavaDoc || number instanceof Integer JavaDoc ||
469                    number instanceof Short JavaDoc || number instanceof Byte JavaDoc ||
470                    (number instanceof BigInteger JavaDoc &&
471                     ((BigInteger JavaDoc)number).bitLength () < 64)) {
472             return format(((Number JavaDoc)number).longValue(), toAppendTo, pos);
473         } else if (number instanceof BigDecimal JavaDoc) {
474             return format((BigDecimal JavaDoc)number, toAppendTo, pos);
475         } else if (number instanceof BigInteger JavaDoc) {
476             return format((BigInteger JavaDoc)number, toAppendTo, pos);
477         } else if (number instanceof Number JavaDoc) {
478             return format(((Number JavaDoc)number).doubleValue(), toAppendTo, pos);
479         } else {
480             throw new IllegalArgumentException JavaDoc("Cannot format given Object as a Number");
481         }
482     }
483
484     /**
485      * Formats a double to produce a string.
486      * @param number The double to format
487      * @param result where the text is to be appended
488      * @param fieldPosition On input: an alignment field, if desired.
489      * On output: the offsets of the alignment field.
490      * @return The formatted number string
491      * @see java.text.FieldPosition
492      */

493     public StringBuffer JavaDoc format(double number, StringBuffer JavaDoc result,
494                                FieldPosition JavaDoc fieldPosition) {
495         fieldPosition.setBeginIndex(0);
496         fieldPosition.setEndIndex(0);
497
498         return format(number, result, fieldPosition.getFieldDelegate());
499     }
500
501     /**
502      * Formats a double to produce a string.
503      * @param number The double to format
504      * @param result where the text is to be appended
505      * @param delegate notified of locations of sub fields
506      * @return The formatted number string
507      */

508     private StringBuffer JavaDoc format(double number, StringBuffer JavaDoc result,
509                                 FieldDelegate delegate) {
510         if (Double.isNaN(number) ||
511            (Double.isInfinite(number) && multiplier == 0)) {
512             int iFieldStart = result.length();
513             result.append(symbols.getNaN());
514             delegate.formatted(INTEGER_FIELD, Field.INTEGER, Field.INTEGER,
515                                iFieldStart, result.length(), result);
516             return result;
517         }
518
519         /* Detecting whether a double is negative is easy with the exception of
520          * the value -0.0. This is a double which has a zero mantissa (and
521          * exponent), but a negative sign bit. It is semantically distinct from
522          * a zero with a positive sign bit, and this distinction is important
523          * to certain kinds of computations. However, it's a little tricky to
524          * detect, since (-0.0 == 0.0) and !(-0.0 < 0.0). How then, you may
525          * ask, does it behave distinctly from +0.0? Well, 1/(-0.0) ==
526          * -Infinity. Proper detection of -0.0 is needed to deal with the
527          * issues raised by bugs 4106658, 4106667, and 4147706. Liu 7/6/98.
528          */

529         boolean isNegative = ((number < 0.0) || (number == 0.0 && 1/number < 0.0)) ^ (multiplier < 0);
530
531         if (multiplier != 1) {
532             number *= multiplier;
533         }
534
535         if (Double.isInfinite(number)) {
536             if (isNegative) {
537                 append(result, negativePrefix, delegate,
538                        getNegativePrefixFieldPositions(), Field.SIGN);
539             } else {
540                 append(result, positivePrefix, delegate,
541                        getPositivePrefixFieldPositions(), Field.SIGN);
542             }
543
544             int iFieldStart = result.length();
545             result.append(symbols.getInfinity());
546             delegate.formatted(INTEGER_FIELD, Field.INTEGER, Field.INTEGER,
547                                iFieldStart, result.length(), result);
548
549             if (isNegative) {
550                 append(result, negativeSuffix, delegate,
551                        getNegativeSuffixFieldPositions(), Field.SIGN);
552             } else {
553                 append(result, positiveSuffix, delegate,
554                        getPositiveSuffixFieldPositions(), Field.SIGN);
555             }
556
557             return result;
558         }
559
560         if (isNegative) {
561             number = -number;
562         }
563
564         // at this point we are guaranteed a nonnegative finite number.
565
assert(number >= 0 && !Double.isInfinite(number));
566
567         synchronized(digitList) {
568             int maxIntDigits = super.getMaximumIntegerDigits();
569             int minIntDigits = super.getMinimumIntegerDigits();
570             int maxFraDigits = super.getMaximumFractionDigits();
571             int minFraDigits = super.getMinimumFractionDigits();
572
573             digitList.set(number, useExponentialNotation ?
574                           maxIntDigits + maxFraDigits : maxFraDigits,
575                           !useExponentialNotation);
576             return subformat(result, delegate, isNegative, false,
577                        maxIntDigits, minIntDigits, maxFraDigits, minFraDigits);
578         }
579     }
580
581     /**
582      * Format a long to produce a string.
583      * @param number The long to format
584      * @param result where the text is to be appended
585      * @param fieldPosition On input: an alignment field, if desired.
586      * On output: the offsets of the alignment field.
587      * @return The formatted number string
588      * @see java.text.FieldPosition
589      */

590     public StringBuffer JavaDoc format(long number, StringBuffer JavaDoc result,
591                                FieldPosition JavaDoc fieldPosition) {
592         fieldPosition.setBeginIndex(0);
593         fieldPosition.setEndIndex(0);
594
595         return format(number, result, fieldPosition.getFieldDelegate());
596     }
597
598     /**
599      * Format a long to produce a string.
600      * @param number The long to format
601      * @param result where the text is to be appended
602      * @param delegate notified of locations of sub fields
603      * @return The formatted number string
604      * @see java.text.FieldPosition
605      */

606     private StringBuffer JavaDoc format(long number, StringBuffer JavaDoc result,
607                                FieldDelegate delegate) {
608         boolean isNegative = (number < 0);
609         if (isNegative) {
610             number = -number;
611         }
612
613         // In general, long values always represent real finite numbers, so
614
// we don't have to check for +/- Infinity or NaN. However, there
615
// is one case we have to be careful of: The multiplier can push
616
// a number near MIN_VALUE or MAX_VALUE outside the legal range. We
617
// check for this before multiplying, and if it happens we use
618
// BigInteger instead.
619
boolean useBigInteger = false;
620         if (number < 0) { // This can only happen if number == Long.MIN_VALUE.
621
if (multiplier != 0) {
622                 useBigInteger = true;
623             }
624         } else if (multiplier != 1 && multiplier != 0) {
625             long cutoff = Long.MAX_VALUE / multiplier;
626             if (cutoff < 0) {
627                 cutoff = -cutoff;
628             }
629             useBigInteger = (number > cutoff);
630         }
631
632         if (useBigInteger) {
633             if (isNegative) {
634                 number = -number;
635             }
636             BigInteger JavaDoc bigIntegerValue = BigInteger.valueOf(number);
637             return format(bigIntegerValue, result, delegate, true);
638         }
639
640         number *= multiplier;
641         if (number == 0) {
642             isNegative = false;
643         } else {
644             if (multiplier < 0) {
645                 number = -number;
646                 isNegative = !isNegative;
647             }
648         }
649
650         synchronized(digitList) {
651             int maxIntDigits = super.getMaximumIntegerDigits();
652             int minIntDigits = super.getMinimumIntegerDigits();
653             int maxFraDigits = super.getMaximumFractionDigits();
654             int minFraDigits = super.getMinimumFractionDigits();
655
656             digitList.set(number,
657                      useExponentialNotation ? maxIntDigits + maxFraDigits : 0);
658
659             return subformat(result, delegate, isNegative, true,
660                        maxIntDigits, minIntDigits, maxFraDigits, minFraDigits);
661         }
662     }
663
664     /**
665      * Formats a BigDecimal to produce a string.
666      * @param number The BigDecimal to format
667      * @param result where the text is to be appended
668      * @param fieldPosition On input: an alignment field, if desired.
669      * On output: the offsets of the alignment field.
670      * @return The formatted number string
671      * @see java.text.FieldPosition
672      */

673     private StringBuffer JavaDoc format(BigDecimal JavaDoc number, StringBuffer JavaDoc result,
674                                 FieldPosition JavaDoc fieldPosition) {
675         fieldPosition.setBeginIndex(0);
676         fieldPosition.setEndIndex(0);
677         return format(number, result, fieldPosition.getFieldDelegate());
678     }
679
680     /**
681      * Formats a BigDecimal to produce a string.
682      * @param number The BigDecimal to format
683      * @param result where the text is to be appended
684      * @param delegate notified of locations of sub fields
685      * @return The formatted number string
686      */

687     private StringBuffer JavaDoc format(BigDecimal JavaDoc number, StringBuffer JavaDoc result,
688                                 FieldDelegate delegate) {
689         if (multiplier != 1) {
690             number = number.multiply(getBigDecimalMultiplier());
691         }
692         boolean isNegative = number.signum() == -1;
693         if (isNegative) {
694             number = number.negate();
695         }
696
697         synchronized(digitList) {
698             int maxIntDigits = getMaximumIntegerDigits();
699             int minIntDigits = getMinimumIntegerDigits();
700             int maxFraDigits = getMaximumFractionDigits();
701             int minFraDigits = getMinimumFractionDigits();
702             int maximumDigits = maxIntDigits + maxFraDigits;
703
704             digitList.set(number, useExponentialNotation ?
705                 ((maximumDigits < 0) ? Integer.MAX_VALUE : maximumDigits) :
706                 maxFraDigits, !useExponentialNotation);
707
708             return subformat(result, delegate, isNegative, false,
709                 maxIntDigits, minIntDigits, maxFraDigits, minFraDigits);
710         }
711     }
712
713     /**
714      * Format a BigInteger to produce a string.
715      * @param number The BigInteger to format
716      * @param result where the text is to be appended
717      * @param fieldPosition On input: an alignment field, if desired.
718      * On output: the offsets of the alignment field.
719      * @return The formatted number string
720      * @see java.text.FieldPosition
721      */

722     private StringBuffer JavaDoc format(BigInteger JavaDoc number, StringBuffer JavaDoc result,
723                                FieldPosition JavaDoc fieldPosition) {
724         fieldPosition.setBeginIndex(0);
725         fieldPosition.setEndIndex(0);
726
727         return format(number, result, fieldPosition.getFieldDelegate(), false);
728     }
729
730     /**
731      * Format a BigInteger to produce a string.
732      * @param number The BigInteger to format
733      * @param result where the text is to be appended
734      * @param delegate notified of locations of sub fields
735      * @return The formatted number string
736      * @see java.text.FieldPosition
737      */

738     private StringBuffer JavaDoc format(BigInteger JavaDoc number, StringBuffer JavaDoc result,
739                                FieldDelegate delegate, boolean formatLong) {
740         if (multiplier != 1) {
741             number = number.multiply(getBigIntegerMultiplier());
742         }
743         boolean isNegative = number.signum() == -1;
744         if (isNegative) {
745             number = number.negate();
746         }
747
748         synchronized(digitList) {
749             int maxIntDigits, minIntDigits, maxFraDigits, minFraDigits, maximumDigits;
750             if (formatLong) {
751                 maxIntDigits = super.getMaximumIntegerDigits();
752                 minIntDigits = super.getMinimumIntegerDigits();
753                 maxFraDigits = super.getMaximumFractionDigits();
754                 minFraDigits = super.getMinimumFractionDigits();
755                 maximumDigits = maxIntDigits + maxFraDigits;
756             } else {
757                 maxIntDigits = getMaximumIntegerDigits();
758                 minIntDigits = getMinimumIntegerDigits();
759                 maxFraDigits = getMaximumFractionDigits();
760                 minFraDigits = getMinimumFractionDigits();
761                 maximumDigits = maxIntDigits + maxFraDigits;
762                 if (maximumDigits < 0) {
763                     maximumDigits = Integer.MAX_VALUE;
764                 }
765             }
766
767             digitList.set(number, useExponentialNotation ? maximumDigits : 0);
768
769             return subformat(result, delegate, isNegative, true,
770                 maxIntDigits, minIntDigits, maxFraDigits, minFraDigits);
771         }
772     }
773
774     /**
775      * Formats an Object producing an <code>AttributedCharacterIterator</code>.
776      * You can use the returned <code>AttributedCharacterIterator</code>
777      * to build the resulting String, as well as to determine information
778      * about the resulting String.
779      * <p>
780      * Each attribute key of the AttributedCharacterIterator will be of type
781      * <code>NumberFormat.Field</code>, with the attribute value being the
782      * same as the attribute key.
783      *
784      * @exception NullPointerException if obj is null.
785      * @exception IllegalArgumentException when the Format cannot format the
786      * given object.
787      * @param obj The object to format
788      * @return AttributedCharacterIterator describing the formatted value.
789      * @since 1.4
790      */

791     public AttributedCharacterIterator JavaDoc formatToCharacterIterator(Object JavaDoc obj) {
792         CharacterIteratorFieldDelegate JavaDoc delegate =
793                          new CharacterIteratorFieldDelegate JavaDoc();
794         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
795
796         if (obj instanceof Double JavaDoc || obj instanceof Float JavaDoc) {
797             format(((Number JavaDoc)obj).doubleValue(), sb, delegate);
798         } else if (obj instanceof Long JavaDoc || obj instanceof Integer JavaDoc ||
799                    obj instanceof Short JavaDoc || obj instanceof Byte JavaDoc) {
800             format(((Number JavaDoc)obj).longValue(), sb, delegate);
801         } else if (obj instanceof BigDecimal JavaDoc) {
802             format((BigDecimal JavaDoc)obj, sb, delegate);
803         } else if (obj instanceof BigInteger JavaDoc) {
804             format((BigInteger JavaDoc)obj, sb, delegate, false);
805         } else if (obj == null) {
806             throw new NullPointerException JavaDoc(
807                 "formatToCharacterIterator must be passed non-null object");
808         } else {
809             throw new IllegalArgumentException JavaDoc(
810                 "Cannot format given Object as a Number");
811         }
812         return delegate.getIterator(sb.toString());
813     }
814
815     /**
816      * Complete the formatting of a finite number. On entry, the digitList must
817      * be filled in with the correct digits.
818      */

819     private StringBuffer JavaDoc subformat(StringBuffer JavaDoc result, FieldDelegate delegate,
820                                    boolean isNegative, boolean isInteger,
821                                    int maxIntDigits, int minIntDigits,
822                                    int maxFraDigits, int minFraDigits) {
823         // NOTE: This isn't required anymore because DigitList takes care of this.
824
//
825
// // The negative of the exponent represents the number of leading
826
// // zeros between the decimal and the first non-zero digit, for
827
// // a value < 0.1 (e.g., for 0.00123, -fExponent == 2). If this
828
// // is more than the maximum fraction digits, then we have an underflow
829
// // for the printed representation. We recognize this here and set
830
// // the DigitList representation to zero in this situation.
831
//
832
// if (-digitList.decimalAt >= getMaximumFractionDigits())
833
// {
834
// digitList.count = 0;
835
// }
836

837         char zero = symbols.getZeroDigit();
838         int zeroDelta = zero - '0'; // '0' is the DigitList representation of zero
839
char grouping = symbols.getGroupingSeparator();
840         char decimal = isCurrencyFormat ?
841             symbols.getMonetaryDecimalSeparator() :
842             symbols.getDecimalSeparator();
843
844         /* Per bug 4147706, DecimalFormat must respect the sign of numbers which
845          * format as zero. This allows sensible computations and preserves
846          * relations such as signum(1/x) = signum(x), where x is +Infinity or
847          * -Infinity. Prior to this fix, we always formatted zero values as if
848          * they were positive. Liu 7/6/98.
849          */

850         if (digitList.isZero()) {
851             digitList.decimalAt = 0; // Normalize
852
}
853
854         if (isNegative) {
855             append(result, negativePrefix, delegate,
856                    getNegativePrefixFieldPositions(), Field.SIGN);
857         } else {
858             append(result, positivePrefix, delegate,
859                    getPositivePrefixFieldPositions(), Field.SIGN);
860         }
861
862         if (useExponentialNotation) {
863             int iFieldStart = result.length();
864             int iFieldEnd = -1;
865             int fFieldStart = -1;
866
867             // Minimum integer digits are handled in exponential format by
868
// adjusting the exponent. For example, 0.01234 with 3 minimum
869
// integer digits is "123.4E-4".
870

871             // Maximum integer digits are interpreted as indicating the
872
// repeating range. This is useful for engineering notation, in
873
// which the exponent is restricted to a multiple of 3. For
874
// example, 0.01234 with 3 maximum integer digits is "12.34e-3".
875
// If maximum integer digits are > 1 and are larger than
876
// minimum integer digits, then minimum integer digits are
877
// ignored.
878
int exponent = digitList.decimalAt;
879             int repeat = maxIntDigits;
880             int minimumIntegerDigits = minIntDigits;
881             if (repeat > 1 && repeat > minIntDigits) {
882                 // A repeating range is defined; adjust to it as follows.
883
// If repeat == 3, we have 6,5,4=>3; 3,2,1=>0; 0,-1,-2=>-3;
884
// -3,-4,-5=>-6, etc. This takes into account that the
885
// exponent we have here is off by one from what we expect;
886
// it is for the format 0.MMMMMx10^n.
887
if (exponent >= 1) {
888                     exponent = ((exponent - 1) / repeat) * repeat;
889                 } else {
890                     // integer division rounds towards 0
891
exponent = ((exponent - repeat) / repeat) * repeat;
892                 }
893                 minimumIntegerDigits = 1;
894             } else {
895                 // No repeating range is defined; use minimum integer digits.
896
exponent -= minimumIntegerDigits;
897             }
898
899             // We now output a minimum number of digits, and more if there
900
// are more digits, up to the maximum number of digits. We