1 /*
   2  * Copyright (c) 1996, 2019, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 /*
  27  * (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
  28  * (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved
  29  *
  30  *   The original version of this source code and documentation is copyrighted
  31  * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These
  32  * materials are provided under terms of a License Agreement between Taligent
  33  * and Sun. This technology is protected by multiple US and International
  34  * patents. This notice and attribution to Taligent may not be removed.
  35  *   Taligent is a registered trademark of Taligent, Inc.
  36  *
  37  */
  38 
  39 package java.text;
  40 
  41 import java.io.IOException;
  42 import java.io.InvalidObjectException;
  43 import java.io.ObjectInputStream;
  44 import java.math.BigDecimal;
  45 import java.math.BigInteger;
  46 import java.math.RoundingMode;
  47 import java.text.spi.NumberFormatProvider;
  48 import java.util.ArrayList;
  49 import java.util.Currency;
  50 import java.util.Locale;
  51 import java.util.concurrent.atomic.AtomicInteger;
  52 import java.util.concurrent.atomic.AtomicLong;
  53 import sun.util.locale.provider.LocaleProviderAdapter;
  54 import sun.util.locale.provider.ResourceBundleBasedAdapter;
  55 
  56 /**
  57  * {@code DecimalFormat} is a concrete subclass of
  58  * {@code NumberFormat} that formats decimal numbers. It has a variety of
  59  * features designed to make it possible to parse and format numbers in any
  60  * locale, including support for Western, Arabic, and Indic digits.  It also
  61  * supports different kinds of numbers, including integers (123), fixed-point
  62  * numbers (123.4), scientific notation (1.23E4), percentages (12%), and
  63  * currency amounts ($123).  All of these can be localized.
  64  *
  65  * <p>To obtain a {@code NumberFormat} for a specific locale, including the
  66  * default locale, call one of {@code NumberFormat}'s factory methods, such
  67  * as {@code getInstance()}.  In general, do not call the
  68  * {@code DecimalFormat} constructors directly, since the
  69  * {@code NumberFormat} factory methods may return subclasses other than
  70  * {@code DecimalFormat}. If you need to customize the format object, do
  71  * something like this:
  72  *
  73  * <blockquote><pre>
  74  * NumberFormat f = NumberFormat.getInstance(loc);
  75  * if (f instanceof DecimalFormat) {
  76  *     ((DecimalFormat) f).setDecimalSeparatorAlwaysShown(true);
  77  * }
  78  * </pre></blockquote>
  79  *
  80  * <p>A {@code DecimalFormat} comprises a <em>pattern</em> and a set of
  81  * <em>symbols</em>.  The pattern may be set directly using
  82  * {@code applyPattern()}, or indirectly using the API methods.  The
  83  * symbols are stored in a {@code DecimalFormatSymbols} object.  When using
  84  * the {@code NumberFormat} factory methods, the pattern and symbols are
  85  * read from localized {@code ResourceBundle}s.
  86  *
  87  * <h3>Patterns</h3>
  88  *
  89  * {@code DecimalFormat} patterns have the following syntax:
  90  * <blockquote><pre>
  91  * <i>Pattern:</i>
  92  *         <i>PositivePattern</i>
  93  *         <i>PositivePattern</i> ; <i>NegativePattern</i>
  94  * <i>PositivePattern:</i>
  95  *         <i>Prefix<sub>opt</sub></i> <i>Number</i> <i>Suffix<sub>opt</sub></i>
  96  * <i>NegativePattern:</i>
  97  *         <i>Prefix<sub>opt</sub></i> <i>Number</i> <i>Suffix<sub>opt</sub></i>
  98  * <i>Prefix:</i>
  99  *         any Unicode characters except \uFFFE, \uFFFF, and special characters
 100  * <i>Suffix:</i>
 101  *         any Unicode characters except \uFFFE, \uFFFF, and special characters
 102  * <i>Number:</i>
 103  *         <i>Integer</i> <i>Exponent<sub>opt</sub></i>
 104  *         <i>Integer</i> . <i>Fraction</i> <i>Exponent<sub>opt</sub></i>
 105  * <i>Integer:</i>
 106  *         <i>MinimumInteger</i>
 107  *         #
 108  *         # <i>Integer</i>
 109  *         # , <i>Integer</i>
 110  * <i>MinimumInteger:</i>
 111  *         0
 112  *         0 <i>MinimumInteger</i>
 113  *         0 , <i>MinimumInteger</i>
 114  * <i>Fraction:</i>
 115  *         <i>MinimumFraction<sub>opt</sub></i> <i>OptionalFraction<sub>opt</sub></i>
 116  * <i>MinimumFraction:</i>
 117  *         0 <i>MinimumFraction<sub>opt</sub></i>
 118  * <i>OptionalFraction:</i>
 119  *         # <i>OptionalFraction<sub>opt</sub></i>
 120  * <i>Exponent:</i>
 121  *         E <i>MinimumExponent</i>
 122  * <i>MinimumExponent:</i>
 123  *         0 <i>MinimumExponent<sub>opt</sub></i>
 124  * </pre></blockquote>
 125  *
 126  * <p>A {@code DecimalFormat} pattern contains a positive and negative
 127  * subpattern, for example, {@code "#,##0.00;(#,##0.00)"}.  Each
 128  * subpattern has a prefix, numeric part, and suffix. The negative subpattern
 129  * is optional; if absent, then the positive subpattern prefixed with the
 130  * localized minus sign ({@code '-'} in most locales) is used as the
 131  * negative subpattern. That is, {@code "0.00"} alone is equivalent to
 132  * {@code "0.00;-0.00"}.  If there is an explicit negative subpattern, it
 133  * serves only to specify the negative prefix and suffix; the number of digits,
 134  * minimal digits, and other characteristics are all the same as the positive
 135  * pattern. That means that {@code "#,##0.0#;(#)"} produces precisely
 136  * the same behavior as {@code "#,##0.0#;(#,##0.0#)"}.
 137  *
 138  * <p>The prefixes, suffixes, and various symbols used for infinity, digits,
 139  * thousands separators, decimal separators, etc. may be set to arbitrary
 140  * values, and they will appear properly during formatting.  However, care must
 141  * be taken that the symbols and strings do not conflict, or parsing will be
 142  * unreliable.  For example, either the positive and negative prefixes or the
 143  * suffixes must be distinct for {@code DecimalFormat.parse()} to be able
 144  * to distinguish positive from negative values.  (If they are identical, then
 145  * {@code DecimalFormat} will behave as if no negative subpattern was
 146  * specified.)  Another example is that the decimal separator and thousands
 147  * separator should be distinct characters, or parsing will be impossible.
 148  *
 149  * <p>The grouping separator is commonly used for thousands, but in some
 150  * countries it separates ten-thousands. The grouping size is a constant number
 151  * of digits between the grouping characters, such as 3 for 100,000,000 or 4 for
 152  * 1,0000,0000.  If you supply a pattern with multiple grouping characters, the
 153  * interval between the last one and the end of the integer is the one that is
 154  * used. So {@code "#,##,###,####"} == {@code "######,####"} ==
 155  * {@code "##,####,####"}.
 156  *
 157  * <h4><a id="special_pattern_character">Special Pattern Characters</a></h4>
 158  *
 159  * <p>Many characters in a pattern are taken literally; they are matched during
 160  * parsing and output unchanged during formatting.  Special characters, on the
 161  * other hand, stand for other characters, strings, or classes of characters.
 162  * They must be quoted, unless noted otherwise, if they are to appear in the
 163  * prefix or suffix as literals.
 164  *
 165  * <p>The characters listed here are used in non-localized patterns.  Localized
 166  * patterns use the corresponding characters taken from this formatter's
 167  * {@code DecimalFormatSymbols} object instead, and these characters lose
 168  * their special status.  Two exceptions are the currency sign and quote, which
 169  * are not localized.
 170  *
 171  * <blockquote>
 172  * <table class="striped">
 173  * <caption style="display:none">Chart showing symbol, location, localized, and meaning.</caption>
 174  * <thead>
 175  *     <tr>
 176  *          <th scope="col" style="text-align:left">Symbol
 177  *          <th scope="col" style="text-align:left">Location
 178  *          <th scope="col" style="text-align:left">Localized?
 179  *          <th scope="col" style="text-align:left">Meaning
 180  * </thead>
 181  * <tbody>
 182  *     <tr style="vertical-align:top">
 183  *          <th scope="row">{@code 0}
 184  *          <td>Number
 185  *          <td>Yes
 186  *          <td>Digit
 187  *     <tr style="vertical-align: top">
 188  *          <th scope="row">{@code #}
 189  *          <td>Number
 190  *          <td>Yes
 191  *          <td>Digit, zero shows as absent
 192  *     <tr style="vertical-align:top">
 193  *          <th scope="row">{@code .}
 194  *          <td>Number
 195  *          <td>Yes
 196  *          <td>Decimal separator or monetary decimal separator
 197  *     <tr style="vertical-align: top">
 198  *          <th scope="row">{@code -}
 199  *          <td>Number
 200  *          <td>Yes
 201  *          <td>Minus sign
 202  *     <tr style="vertical-align:top">
 203  *          <th scope="row">{@code ,}
 204  *          <td>Number
 205  *          <td>Yes
 206  *          <td>Grouping separator
 207  *     <tr style="vertical-align: top">
 208  *          <th scope="row">{@code E}
 209  *          <td>Number
 210  *          <td>Yes
 211  *          <td>Separates mantissa and exponent in scientific notation.
 212  *              <em>Need not be quoted in prefix or suffix.</em>
 213  *     <tr style="vertical-align:top">
 214  *          <th scope="row">{@code ;}
 215  *          <td>Subpattern boundary
 216  *          <td>Yes
 217  *          <td>Separates positive and negative subpatterns
 218  *     <tr style="vertical-align: top">
 219  *          <th scope="row">{@code %}
 220  *          <td>Prefix or suffix
 221  *          <td>Yes
 222  *          <td>Multiply by 100 and show as percentage
 223  *     <tr style="vertical-align:top">
 224  *          <th scope="row">{@code \u2030}
 225  *          <td>Prefix or suffix
 226  *          <td>Yes
 227  *          <td>Multiply by 1000 and show as per mille value
 228  *     <tr style="vertical-align: top">
 229  *          <th scope="row">{@code ¤} ({@code \u00A4})
 230  *          <td>Prefix or suffix
 231  *          <td>No
 232  *          <td>Currency sign, replaced by currency symbol.  If
 233  *              doubled, replaced by international currency symbol.
 234  *              If present in a pattern, the monetary decimal separator
 235  *              is used instead of the decimal separator.
 236  *     <tr style="vertical-align:top">
 237  *          <th scope="row">{@code '}
 238  *          <td>Prefix or suffix
 239  *          <td>No
 240  *          <td>Used to quote special characters in a prefix or suffix,
 241  *              for example, {@code "'#'#"} formats 123 to
 242  *              {@code "#123"}.  To create a single quote
 243  *              itself, use two in a row: {@code "# o''clock"}.
 244  * </tbody>
 245  * </table>
 246  * </blockquote>
 247  *
 248  * <h4>Scientific Notation</h4>
 249  *
 250  * <p>Numbers in scientific notation are expressed as the product of a mantissa
 251  * and a power of ten, for example, 1234 can be expressed as 1.234 x 10^3.  The
 252  * mantissa is often in the range 1.0 &le; x {@literal <} 10.0, but it need not
 253  * be.
 254  * {@code DecimalFormat} can be instructed to format and parse scientific
 255  * notation <em>only via a pattern</em>; there is currently no factory method
 256  * that creates a scientific notation format.  In a pattern, the exponent
 257  * character immediately followed by one or more digit characters indicates
 258  * scientific notation.  Example: {@code "0.###E0"} formats the number
 259  * 1234 as {@code "1.234E3"}.
 260  *
 261  * <ul>
 262  * <li>The number of digit characters after the exponent character gives the
 263  * minimum exponent digit count.  There is no maximum.  Negative exponents are
 264  * formatted using the localized minus sign, <em>not</em> the prefix and suffix
 265  * from the pattern.  This allows patterns such as {@code "0.###E0 m/s"}.
 266  *
 267  * <li>The minimum and maximum number of integer digits are interpreted
 268  * together:
 269  *
 270  * <ul>
 271  * <li>If the maximum number of integer digits is greater than their minimum number
 272  * and greater than 1, it forces the exponent to be a multiple of the maximum
 273  * number of integer digits, and the minimum number of integer digits to be
 274  * interpreted as 1.  The most common use of this is to generate
 275  * <em>engineering notation</em>, in which the exponent is a multiple of three,
 276  * e.g., {@code "##0.#####E0"}. Using this pattern, the number 12345
 277  * formats to {@code "12.345E3"}, and 123456 formats to
 278  * {@code "123.456E3"}.
 279  *
 280  * <li>Otherwise, the minimum number of integer digits is achieved by adjusting the
 281  * exponent.  Example: 0.00123 formatted with {@code "00.###E0"} yields
 282  * {@code "12.3E-4"}.
 283  * </ul>
 284  *
 285  * <li>The number of significant digits in the mantissa is the sum of the
 286  * <em>minimum integer</em> and <em>maximum fraction</em> digits, and is
 287  * unaffected by the maximum integer digits.  For example, 12345 formatted with
 288  * {@code "##0.##E0"} is {@code "12.3E3"}. To show all digits, set
 289  * the significant digits count to zero.  The number of significant digits
 290  * does not affect parsing.
 291  *
 292  * <li>Exponential patterns may not contain grouping separators.
 293  * </ul>
 294  *
 295  * <h4>Rounding</h4>
 296  *
 297  * {@code DecimalFormat} provides rounding modes defined in
 298  * {@link java.math.RoundingMode} for formatting.  By default, it uses
 299  * {@link java.math.RoundingMode#HALF_EVEN RoundingMode.HALF_EVEN}.
 300  *
 301  * <h4>Digits</h4>
 302  *
 303  * For formatting, {@code DecimalFormat} uses the ten consecutive
 304  * characters starting with the localized zero digit defined in the
 305  * {@code DecimalFormatSymbols} object as digits. For parsing, these
 306  * digits as well as all Unicode decimal digits, as defined by
 307  * {@link Character#digit Character.digit}, are recognized.
 308  *
 309  * <h4>Special Values</h4>
 310  *
 311  * <p>{@code NaN} is formatted as a string, which typically has a single character
 312  * {@code \uFFFD}.  This string is determined by the
 313  * {@code DecimalFormatSymbols} object.  This is the only value for which
 314  * the prefixes and suffixes are not used.
 315  *
 316  * <p>Infinity is formatted as a string, which typically has a single character
 317  * {@code \u221E}, with the positive or negative prefixes and suffixes
 318  * applied.  The infinity string is determined by the
 319  * {@code DecimalFormatSymbols} object.
 320  *
 321  * <p>Negative zero ({@code "-0"}) parses to
 322  * <ul>
 323  * <li>{@code BigDecimal(0)} if {@code isParseBigDecimal()} is
 324  * true,
 325  * <li>{@code Long(0)} if {@code isParseBigDecimal()} is false
 326  *     and {@code isParseIntegerOnly()} is true,
 327  * <li>{@code Double(-0.0)} if both {@code isParseBigDecimal()}
 328  * and {@code isParseIntegerOnly()} are false.
 329  * </ul>
 330  *
 331  * <h4><a id="synchronization">Synchronization</a></h4>
 332  *
 333  * <p>
 334  * Decimal formats are generally not synchronized.
 335  * It is recommended to create separate format instances for each thread.
 336  * If multiple threads access a format concurrently, it must be synchronized
 337  * externally.
 338  *
 339  * <h4>Example</h4>
 340  *
 341  * <blockquote><pre>{@code
 342  * <strong>// Print out a number using the localized number, integer, currency,
 343  * // and percent format for each locale</strong>
 344  * Locale[] locales = NumberFormat.getAvailableLocales();
 345  * double myNumber = -1234.56;
 346  * NumberFormat form;
 347  * for (int j = 0; j < 4; ++j) {
 348  *     System.out.println("FORMAT");
 349  *     for (int i = 0; i < locales.length; ++i) {
 350  *         if (locales[i].getCountry().length() == 0) {
 351  *            continue; // Skip language-only locales
 352  *         }
 353  *         System.out.print(locales[i].getDisplayName());
 354  *         switch (j) {
 355  *         case 0:
 356  *             form = NumberFormat.getInstance(locales[i]); break;
 357  *         case 1:
 358  *             form = NumberFormat.getIntegerInstance(locales[i]); break;
 359  *         case 2:
 360  *             form = NumberFormat.getCurrencyInstance(locales[i]); break;
 361  *         default:
 362  *             form = NumberFormat.getPercentInstance(locales[i]); break;
 363  *         }
 364  *         if (form instanceof DecimalFormat) {
 365  *             System.out.print(": " + ((DecimalFormat) form).toPattern());
 366  *         }
 367  *         System.out.print(" -> " + form.format(myNumber));
 368  *         try {
 369  *             System.out.println(" -> " + form.parse(form.format(myNumber)));
 370  *         } catch (ParseException e) {}
 371  *     }
 372  * }
 373  * }</pre></blockquote>
 374  *
 375  * @see          <a href="http://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html">Java Tutorial</a>
 376  * @see          NumberFormat
 377  * @see          DecimalFormatSymbols
 378  * @see          ParsePosition
 379  * @author       Mark Davis
 380  * @author       Alan Liu
 381  * @since 1.1
 382  */
 383 public class DecimalFormat extends NumberFormat {
 384 
 385     /**
 386      * Creates a DecimalFormat using the default pattern and symbols
 387      * for the default {@link java.util.Locale.Category#FORMAT FORMAT} locale.
 388      * This is a convenient way to obtain a
 389      * DecimalFormat when internationalization is not the main concern.
 390      * <p>
 391      * To obtain standard formats for a given locale, use the factory methods
 392      * on NumberFormat such as getNumberInstance. These factories will
 393      * return the most appropriate sub-class of NumberFormat for a given
 394      * locale.
 395      *
 396      * @see java.text.NumberFormat#getInstance
 397      * @see java.text.NumberFormat#getNumberInstance
 398      * @see java.text.NumberFormat#getCurrencyInstance
 399      * @see java.text.NumberFormat#getPercentInstance
 400      */
 401     public DecimalFormat() {
 402         // Get the pattern for the default locale.
 403         Locale def = Locale.getDefault(Locale.Category.FORMAT);
 404         LocaleProviderAdapter adapter = LocaleProviderAdapter.getAdapter(NumberFormatProvider.class, def);
 405         if (!(adapter instanceof ResourceBundleBasedAdapter)) {
 406             adapter = LocaleProviderAdapter.getResourceBundleBased();
 407         }
 408         String[] all = adapter.getLocaleResources(def).getNumberPatterns();
 409 
 410         // Always applyPattern after the symbols are set
 411         this.symbols = DecimalFormatSymbols.getInstance(def);
 412         applyPattern(all[0], false);
 413     }
 414 
 415 
 416     /**
 417      * Creates a DecimalFormat using the given pattern and the symbols
 418      * for the default {@link java.util.Locale.Category#FORMAT FORMAT} locale.
 419      * This is a convenient way to obtain a
 420      * DecimalFormat when internationalization is not the main concern.
 421      * <p>
 422      * To obtain standard formats for a given locale, use the factory methods
 423      * on NumberFormat such as getNumberInstance. These factories will
 424      * return the most appropriate sub-class of NumberFormat for a given
 425      * locale.
 426      *
 427      * @param pattern a non-localized pattern string.
 428      * @exception NullPointerException if {@code pattern} is null
 429      * @exception IllegalArgumentException if the given pattern is invalid.
 430      * @see java.text.NumberFormat#getInstance
 431      * @see java.text.NumberFormat#getNumberInstance
 432      * @see java.text.NumberFormat#getCurrencyInstance
 433      * @see java.text.NumberFormat#getPercentInstance
 434      */
 435     public DecimalFormat(String pattern) {
 436         // Always applyPattern after the symbols are set
 437         this.symbols = DecimalFormatSymbols.getInstance(Locale.getDefault(Locale.Category.FORMAT));
 438         applyPattern(pattern, false);
 439     }
 440 
 441 
 442     /**
 443      * Creates a DecimalFormat using the given pattern and symbols.
 444      * Use this constructor when you need to completely customize the
 445      * behavior of the format.
 446      * <p>
 447      * To obtain standard formats for a given
 448      * locale, use the factory methods on NumberFormat such as
 449      * getInstance or getCurrencyInstance. If you need only minor adjustments
 450      * to a standard format, you can modify the format returned by
 451      * a NumberFormat factory method.
 452      *
 453      * @param pattern a non-localized pattern string
 454      * @param symbols the set of symbols to be used
 455      * @exception NullPointerException if any of the given arguments is null
 456      * @exception IllegalArgumentException if the given pattern is invalid
 457      * @see java.text.NumberFormat#getInstance
 458      * @see java.text.NumberFormat#getNumberInstance
 459      * @see java.text.NumberFormat#getCurrencyInstance
 460      * @see java.text.NumberFormat#getPercentInstance
 461      * @see java.text.DecimalFormatSymbols
 462      */
 463     public DecimalFormat (String pattern, DecimalFormatSymbols symbols) {
 464         // Always applyPattern after the symbols are set
 465         this.symbols = (DecimalFormatSymbols)symbols.clone();
 466         applyPattern(pattern, false);
 467     }
 468 
 469 
 470     // Overrides
 471     /**
 472      * Formats a number and appends the resulting text to the given string
 473      * buffer.
 474      * The number can be of any subclass of {@link java.lang.Number}.
 475      * <p>
 476      * This implementation uses the maximum precision permitted.
 477      * @param number     the number to format
 478      * @param toAppendTo the {@code StringBuffer} to which the formatted
 479      *                   text is to be appended
 480      * @param pos        keeps track on the position of the field within the
 481      *                   returned string. For example, for formatting a number
 482      *                   {@code 1234567.89} in {@code Locale.US} locale,
 483      *                   if the given {@code fieldPosition} is
 484      *                   {@link NumberFormat#INTEGER_FIELD}, the begin index
 485      *                   and end index of {@code fieldPosition} will be set
 486      *                   to 0 and 9, respectively for the output string
 487      *                   {@code 1,234,567.89}.
 488      * @return           the value passed in as {@code toAppendTo}
 489      * @exception        IllegalArgumentException if {@code number} is
 490      *                   null or not an instance of {@code Number}.
 491      * @exception        NullPointerException if {@code toAppendTo} or
 492      *                   {@code pos} is null
 493      * @exception        ArithmeticException if rounding is needed with rounding
 494      *                   mode being set to RoundingMode.UNNECESSARY
 495      * @see              java.text.FieldPosition
 496      */
 497     @Override
 498     public final StringBuffer format(Object number,
 499                                      StringBuffer toAppendTo,
 500                                      FieldPosition pos) {
 501         if (number instanceof Long || number instanceof Integer ||
 502                    number instanceof Short || number instanceof Byte ||
 503                    number instanceof AtomicInteger ||
 504                    number instanceof AtomicLong ||
 505                    (number instanceof BigInteger &&
 506                     ((BigInteger)number).bitLength () < 64)) {
 507             return format(((Number)number).longValue(), toAppendTo, pos);
 508         } else if (number instanceof BigDecimal) {
 509             return format((BigDecimal)number, toAppendTo, pos);
 510         } else if (number instanceof BigInteger) {
 511             return format((BigInteger)number, toAppendTo, pos);
 512         } else if (number instanceof Number) {
 513             return format(((Number)number).doubleValue(), toAppendTo, pos);
 514         } else {
 515             throw new IllegalArgumentException("Cannot format given Object as a Number");
 516         }
 517     }
 518 
 519     /**
 520      * Formats a double to produce a string.
 521      * @param number    The double to format
 522      * @param result    where the text is to be appended
 523      * @param fieldPosition    keeps track on the position of the field within
 524      *                         the returned string. For example, for formatting
 525      *                         a number {@code 1234567.89} in {@code Locale.US}
 526      *                         locale, if the given {@code fieldPosition} is
 527      *                         {@link NumberFormat#INTEGER_FIELD}, the begin index
 528      *                         and end index of {@code fieldPosition} will be set
 529      *                         to 0 and 9, respectively for the output string
 530      *                         {@code 1,234,567.89}.
 531      * @exception NullPointerException if {@code result} or
 532      *            {@code fieldPosition} is {@code null}
 533      * @exception ArithmeticException if rounding is needed with rounding
 534      *            mode being set to RoundingMode.UNNECESSARY
 535      * @return The formatted number string
 536      * @see java.text.FieldPosition
 537      */
 538     @Override
 539     public StringBuffer format(double number, StringBuffer result,
 540                                FieldPosition fieldPosition) {
 541         // If fieldPosition is a DontCareFieldPosition instance we can
 542         // try to go to fast-path code.
 543         boolean tryFastPath = false;
 544         if (fieldPosition == DontCareFieldPosition.INSTANCE)
 545             tryFastPath = true;
 546         else {
 547             fieldPosition.setBeginIndex(0);
 548             fieldPosition.setEndIndex(0);
 549         }
 550 
 551         if (tryFastPath) {
 552             String tempResult = fastFormat(number);
 553             if (tempResult != null) {
 554                 result.append(tempResult);
 555                 return result;
 556             }
 557         }
 558 
 559         // if fast-path could not work, we fallback to standard code.
 560         return format(number, result, fieldPosition.getFieldDelegate());
 561     }
 562 
 563     /**
 564      * Formats a double to produce a string.
 565      * @param number    The double to format
 566      * @param result    where the text is to be appended
 567      * @param delegate notified of locations of sub fields
 568      * @exception       ArithmeticException if rounding is needed with rounding
 569      *                  mode being set to RoundingMode.UNNECESSARY
 570      * @return The formatted number string
 571      */
 572     StringBuffer format(double number, StringBuffer result,
 573                                 FieldDelegate delegate) {
 574 
 575         boolean nanOrInfinity = handleNaN(number, result, delegate);
 576         if (nanOrInfinity) {
 577             return result;
 578         }
 579 
 580         /* Detecting whether a double is negative is easy with the exception of
 581          * the value -0.0.  This is a double which has a zero mantissa (and
 582          * exponent), but a negative sign bit.  It is semantically distinct from
 583          * a zero with a positive sign bit, and this distinction is important
 584          * to certain kinds of computations.  However, it's a little tricky to
 585          * detect, since (-0.0 == 0.0) and !(-0.0 < 0.0).  How then, you may
 586          * ask, does it behave distinctly from +0.0?  Well, 1/(-0.0) ==
 587          * -Infinity.  Proper detection of -0.0 is needed to deal with the
 588          * issues raised by bugs 4106658, 4106667, and 4147706.  Liu 7/6/98.
 589          */
 590         boolean isNegative = ((number < 0.0) || (number == 0.0 && 1/number < 0.0)) ^ (multiplier < 0);
 591 
 592         if (multiplier != 1) {
 593             number *= multiplier;
 594         }
 595 
 596         nanOrInfinity = handleInfinity(number, result, delegate, isNegative);
 597         if (nanOrInfinity) {
 598             return result;
 599         }
 600 
 601         if (isNegative) {
 602             number = -number;
 603         }
 604 
 605         // at this point we are guaranteed a nonnegative finite number.
 606         assert (number >= 0 && !Double.isInfinite(number));
 607         return doubleSubformat(number, result, delegate, isNegative);
 608     }
 609 
 610     /**
 611      * Checks if the given {@code number} is {@code Double.NaN}. if yes;
 612      * appends the NaN symbol to the result string. The NaN string is
 613      * determined by the DecimalFormatSymbols object.
 614      * @param number the double number to format
 615      * @param result where the text is to be appended
 616      * @param delegate notified of locations of sub fields
 617      * @return true, if number is a NaN; false otherwise
 618      */
 619     boolean handleNaN(double number, StringBuffer result,
 620             FieldDelegate delegate) {
 621         if (Double.isNaN(number)
 622                 || (Double.isInfinite(number) && multiplier == 0)) {
 623             int iFieldStart = result.length();
 624             result.append(symbols.getNaN());
 625             delegate.formatted(INTEGER_FIELD, Field.INTEGER, Field.INTEGER,
 626                     iFieldStart, result.length(), result);
 627             return true;
 628         }
 629         return false;
 630     }
 631 
 632     /**
 633      * Checks if the given {@code number} is {@code Double.NEGATIVE_INFINITY}
 634      * or {@code Double.POSITIVE_INFINITY}. if yes;
 635      * appends the infinity string to the result string. The infinity string is
 636      * determined by the DecimalFormatSymbols object.
 637      * @param number the double number to format
 638      * @param result where the text is to be appended
 639      * @param delegate notified of locations of sub fields
 640      * @param isNegative whether the given {@code number} is negative
 641      * @return true, if number is a {@code Double.NEGATIVE_INFINITY} or
 642      *         {@code Double.POSITIVE_INFINITY}; false otherwise
 643      */
 644     boolean handleInfinity(double number, StringBuffer result,
 645             FieldDelegate delegate, boolean isNegative) {
 646         if (Double.isInfinite(number)) {
 647             if (isNegative) {
 648                 append(result, negativePrefix, delegate,
 649                        getNegativePrefixFieldPositions(), Field.SIGN);
 650             } else {
 651                 append(result, positivePrefix, delegate,
 652                        getPositivePrefixFieldPositions(), Field.SIGN);
 653             }
 654 
 655             int iFieldStart = result.length();
 656             result.append(symbols.getInfinity());
 657             delegate.formatted(INTEGER_FIELD, Field.INTEGER, Field.INTEGER,
 658                                iFieldStart, result.length(), result);
 659 
 660             if (isNegative) {
 661                 append(result, negativeSuffix, delegate,
 662                        getNegativeSuffixFieldPositions(), Field.SIGN);
 663             } else {
 664                 append(result, positiveSuffix, delegate,
 665                        getPositiveSuffixFieldPositions(), Field.SIGN);
 666             }
 667 
 668             return true;
 669         }
 670         return false;
 671     }
 672 
 673     StringBuffer doubleSubformat(double number, StringBuffer result,
 674             FieldDelegate delegate, boolean isNegative) {
 675         synchronized (digitList) {
 676             int maxIntDigits = super.getMaximumIntegerDigits();
 677             int minIntDigits = super.getMinimumIntegerDigits();
 678             int maxFraDigits = super.getMaximumFractionDigits();
 679             int minFraDigits = super.getMinimumFractionDigits();
 680 
 681             digitList.set(isNegative, number, useExponentialNotation
 682                     ? maxIntDigits + maxFraDigits : maxFraDigits,
 683                     !useExponentialNotation);
 684             return subformat(result, delegate, isNegative, false,
 685                     maxIntDigits, minIntDigits, maxFraDigits, minFraDigits);
 686         }
 687     }
 688 
 689     /**
 690      * Format a long to produce a string.
 691      * @param number    The long to format
 692      * @param result    where the text is to be appended
 693      * @param fieldPosition    keeps track on the position of the field within
 694      *                         the returned string. For example, for formatting
 695      *                         a number {@code 123456789} in {@code Locale.US}
 696      *                         locale, if the given {@code fieldPosition} is
 697      *                         {@link NumberFormat#INTEGER_FIELD}, the begin index
 698      *                         and end index of {@code fieldPosition} will be set
 699      *                         to 0 and 11, respectively for the output string
 700      *                         {@code 123,456,789}.
 701      * @exception       NullPointerException if {@code result} or
 702      *                  {@code fieldPosition} is {@code null}
 703      * @exception       ArithmeticException if rounding is needed with rounding
 704      *                  mode being set to RoundingMode.UNNECESSARY
 705      * @return The formatted number string
 706      * @see java.text.FieldPosition
 707      */
 708     @Override
 709     public StringBuffer format(long number, StringBuffer result,
 710                                FieldPosition fieldPosition) {
 711         fieldPosition.setBeginIndex(0);
 712         fieldPosition.setEndIndex(0);
 713 
 714         return format(number, result, fieldPosition.getFieldDelegate());
 715     }
 716 
 717     /**
 718      * Format a long to produce a string.
 719      * @param number    The long to format
 720      * @param result    where the text is to be appended
 721      * @param delegate notified of locations of sub fields
 722      * @return The formatted number string
 723      * @exception        ArithmeticException if rounding is needed with rounding
 724      *                   mode being set to RoundingMode.UNNECESSARY
 725      * @see java.text.FieldPosition
 726      */
 727     StringBuffer format(long number, StringBuffer result,
 728                                FieldDelegate delegate) {
 729         boolean isNegative = (number < 0);
 730         if (isNegative) {
 731             number = -number;
 732         }
 733 
 734         // In general, long values always represent real finite numbers, so
 735         // we don't have to check for +/- Infinity or NaN.  However, there
 736         // is one case we have to be careful of:  The multiplier can push
 737         // a number near MIN_VALUE or MAX_VALUE outside the legal range.  We
 738         // check for this before multiplying, and if it happens we use
 739         // BigInteger instead.
 740         boolean useBigInteger = false;
 741         if (number < 0) { // This can only happen if number == Long.MIN_VALUE.
 742             if (multiplier != 0) {
 743                 useBigInteger = true;
 744             }
 745         } else if (multiplier != 1 && multiplier != 0) {
 746             long cutoff = Long.MAX_VALUE / multiplier;
 747             if (cutoff < 0) {
 748                 cutoff = -cutoff;
 749             }
 750             useBigInteger = (number > cutoff);
 751         }
 752 
 753         if (useBigInteger) {
 754             if (isNegative) {
 755                 number = -number;
 756             }
 757             BigInteger bigIntegerValue = BigInteger.valueOf(number);
 758             return format(bigIntegerValue, result, delegate, true);
 759         }
 760 
 761         number *= multiplier;
 762         if (number == 0) {
 763             isNegative = false;
 764         } else {
 765             if (multiplier < 0) {
 766                 number = -number;
 767                 isNegative = !isNegative;
 768             }
 769         }
 770 
 771         synchronized(digitList) {
 772             int maxIntDigits = super.getMaximumIntegerDigits();
 773             int minIntDigits = super.getMinimumIntegerDigits();
 774             int maxFraDigits = super.getMaximumFractionDigits();
 775             int minFraDigits = super.getMinimumFractionDigits();
 776 
 777             digitList.set(isNegative, number,
 778                      useExponentialNotation ? maxIntDigits + maxFraDigits : 0);
 779 
 780             return subformat(result, delegate, isNegative, true,
 781                        maxIntDigits, minIntDigits, maxFraDigits, minFraDigits);
 782         }
 783     }
 784 
 785     /**
 786      * Formats a BigDecimal to produce a string.
 787      * @param number    The BigDecimal to format
 788      * @param result    where the text is to be appended
 789      * @param fieldPosition    keeps track on the position of the field within
 790      *                         the returned string. For example, for formatting
 791      *                         a number {@code 1234567.89} in {@code Locale.US}
 792      *                         locale, if the given {@code fieldPosition} is
 793      *                         {@link NumberFormat#INTEGER_FIELD}, the begin index
 794      *                         and end index of {@code fieldPosition} will be set
 795      *                         to 0 and 9, respectively for the output string
 796      *                         {@code 1,234,567.89}.
 797      * @return The formatted number string
 798      * @exception        ArithmeticException if rounding is needed with rounding
 799      *                   mode being set to RoundingMode.UNNECESSARY
 800      * @see java.text.FieldPosition
 801      */
 802     private StringBuffer format(BigDecimal number, StringBuffer result,
 803                                 FieldPosition fieldPosition) {
 804         fieldPosition.setBeginIndex(0);
 805         fieldPosition.setEndIndex(0);
 806         return format(number, result, fieldPosition.getFieldDelegate());
 807     }
 808 
 809     /**
 810      * Formats a BigDecimal to produce a string.
 811      * @param number    The BigDecimal to format
 812      * @param result    where the text is to be appended
 813      * @param delegate notified of locations of sub fields
 814      * @exception        ArithmeticException if rounding is needed with rounding
 815      *                   mode being set to RoundingMode.UNNECESSARY
 816      * @return The formatted number string
 817      */
 818     StringBuffer format(BigDecimal number, StringBuffer result,
 819                                 FieldDelegate delegate) {
 820         if (multiplier != 1) {
 821             number = number.multiply(getBigDecimalMultiplier());
 822         }
 823         boolean isNegative = number.signum() == -1;
 824         if (isNegative) {
 825             number = number.negate();
 826         }
 827 
 828         synchronized(digitList) {
 829             int maxIntDigits = getMaximumIntegerDigits();
 830             int minIntDigits = getMinimumIntegerDigits();
 831             int maxFraDigits = getMaximumFractionDigits();
 832             int minFraDigits = getMinimumFractionDigits();
 833             int maximumDigits = maxIntDigits + maxFraDigits;
 834 
 835             digitList.set(isNegative, number, useExponentialNotation ?
 836                 ((maximumDigits < 0) ? Integer.MAX_VALUE : maximumDigits) :
 837                 maxFraDigits, !useExponentialNotation);
 838 
 839             return subformat(result, delegate, isNegative, false,
 840                 maxIntDigits, minIntDigits, maxFraDigits, minFraDigits);
 841         }
 842     }
 843 
 844     /**
 845      * Format a BigInteger to produce a string.
 846      * @param number    The BigInteger to format
 847      * @param result    where the text is to be appended
 848      * @param fieldPosition    keeps track on the position of the field within
 849      *                         the returned string. For example, for formatting
 850      *                         a number {@code 123456789} in {@code Locale.US}
 851      *                         locale, if the given {@code fieldPosition} is
 852      *                         {@link NumberFormat#INTEGER_FIELD}, the begin index
 853      *                         and end index of {@code fieldPosition} will be set
 854      *                         to 0 and 11, respectively for the output string
 855      *                         {@code 123,456,789}.
 856      * @return The formatted number string
 857      * @exception        ArithmeticException if rounding is needed with rounding
 858      *                   mode being set to RoundingMode.UNNECESSARY
 859      * @see java.text.FieldPosition
 860      */
 861     private StringBuffer format(BigInteger number, StringBuffer result,
 862                                FieldPosition fieldPosition) {
 863         fieldPosition.setBeginIndex(0);
 864         fieldPosition.setEndIndex(0);
 865 
 866         return format(number, result, fieldPosition.getFieldDelegate(), false);
 867     }
 868 
 869     /**
 870      * Format a BigInteger to produce a string.
 871      * @param number    The BigInteger to format
 872      * @param result    where the text is to be appended
 873      * @param delegate notified of locations of sub fields
 874      * @return The formatted number string
 875      * @exception        ArithmeticException if rounding is needed with rounding
 876      *                   mode being set to RoundingMode.UNNECESSARY
 877      * @see java.text.FieldPosition
 878      */
 879     StringBuffer format(BigInteger number, StringBuffer result,
 880                                FieldDelegate delegate, boolean formatLong) {
 881         if (multiplier != 1) {
 882             number = number.multiply(getBigIntegerMultiplier());
 883         }
 884         boolean isNegative = number.signum() == -1;
 885         if (isNegative) {
 886             number = number.negate();
 887         }
 888 
 889         synchronized(digitList) {
 890             int maxIntDigits, minIntDigits, maxFraDigits, minFraDigits, maximumDigits;
 891             if (formatLong) {
 892                 maxIntDigits = super.getMaximumIntegerDigits();
 893                 minIntDigits = super.getMinimumIntegerDigits();
 894                 maxFraDigits = super.getMaximumFractionDigits();
 895                 minFraDigits = super.getMinimumFractionDigits();
 896                 maximumDigits = maxIntDigits + maxFraDigits;
 897             } else {
 898                 maxIntDigits = getMaximumIntegerDigits();
 899                 minIntDigits = getMinimumIntegerDigits();
 900                 maxFraDigits = getMaximumFractionDigits();
 901                 minFraDigits = getMinimumFractionDigits();
 902                 maximumDigits = maxIntDigits + maxFraDigits;
 903                 if (maximumDigits < 0) {
 904                     maximumDigits = Integer.MAX_VALUE;
 905                 }
 906             }
 907 
 908             digitList.set(isNegative, number,
 909                           useExponentialNotation ? maximumDigits : 0);
 910 
 911             return subformat(result, delegate, isNegative, true,
 912                 maxIntDigits, minIntDigits, maxFraDigits, minFraDigits);
 913         }
 914     }
 915 
 916     /**
 917      * Formats an Object producing an {@code AttributedCharacterIterator}.
 918      * You can use the returned {@code AttributedCharacterIterator}
 919      * to build the resulting String, as well as to determine information
 920      * about the resulting String.
 921      * <p>
 922      * Each attribute key of the AttributedCharacterIterator will be of type
 923      * {@code NumberFormat.Field}, with the attribute value being the
 924      * same as the attribute key.
 925      *
 926      * @exception NullPointerException if obj is null.
 927      * @exception IllegalArgumentException when the Format cannot format the
 928      *            given object.
 929      * @exception        ArithmeticException if rounding is needed with rounding
 930      *                   mode being set to RoundingMode.UNNECESSARY
 931      * @param obj The object to format
 932      * @return AttributedCharacterIterator describing the formatted value.
 933      * @since 1.4
 934      */
 935     @Override
 936     public AttributedCharacterIterator formatToCharacterIterator(Object obj) {
 937         CharacterIteratorFieldDelegate delegate =
 938                          new CharacterIteratorFieldDelegate();
 939         StringBuffer sb = new StringBuffer();
 940 
 941         if (obj instanceof Double || obj instanceof Float) {
 942             format(((Number)obj).doubleValue(), sb, delegate);
 943         } else if (obj instanceof Long || obj instanceof Integer ||
 944                    obj instanceof Short || obj instanceof Byte ||
 945                    obj instanceof AtomicInteger || obj instanceof AtomicLong) {
 946             format(((Number)obj).longValue(), sb, delegate);
 947         } else if (obj instanceof BigDecimal) {
 948             format((BigDecimal)obj, sb, delegate);
 949         } else if (obj instanceof BigInteger) {
 950             format((BigInteger)obj, sb, delegate, false);
 951         } else if (obj == null) {
 952             throw new NullPointerException(
 953                 "formatToCharacterIterator must be passed non-null object");
 954         } else {
 955             throw new IllegalArgumentException(
 956                 "Cannot format given Object as a Number");
 957         }
 958         return delegate.getIterator(sb.toString());
 959     }
 960 
 961     // ==== Begin fast-path formatting logic for double =========================
 962 
 963     /* Fast-path formatting will be used for format(double ...) methods iff a
 964      * number of conditions are met (see checkAndSetFastPathStatus()):
 965      * - Only if instance properties meet the right predefined conditions.
 966      * - The abs value of the double to format is <= Integer.MAX_VALUE.
 967      *
 968      * The basic approach is to split the binary to decimal conversion of a
 969      * double value into two phases:
 970      * * The conversion of the integer portion of the double.
 971      * * The conversion of the fractional portion of the double
 972      *   (limited to two or three digits).
 973      *
 974      * The isolation and conversion of the integer portion of the double is
 975      * straightforward. The conversion of the fraction is more subtle and relies
 976      * on some rounding properties of double to the decimal precisions in
 977      * question.  Using the terminology of BigDecimal, this fast-path algorithm
 978      * is applied when a double value has a magnitude less than Integer.MAX_VALUE
 979      * and rounding is to nearest even and the destination format has two or
 980      * three digits of *scale* (digits after the decimal point).
 981      *
 982      * Under a rounding to nearest even policy, the returned result is a digit
 983      * string of a number in the (in this case decimal) destination format
 984      * closest to the exact numerical value of the (in this case binary) input
 985      * value.  If two destination format numbers are equally distant, the one
 986      * with the last digit even is returned.  To compute such a correctly rounded
 987      * value, some information about digits beyond the smallest returned digit
 988      * position needs to be consulted.
 989      *
 990      * In general, a guard digit, a round digit, and a sticky *bit* are needed
 991      * beyond the returned digit position.  If the discarded portion of the input
 992      * is sufficiently large, the returned digit string is incremented.  In round
 993      * to nearest even, this threshold to increment occurs near the half-way
 994      * point between digits.  The sticky bit records if there are any remaining
 995      * trailing digits of the exact input value in the new format; the sticky bit
 996      * is consulted only in close to half-way rounding cases.
 997      *
 998      * Given the computation of the digit and bit values, rounding is then
 999      * reduced to a table lookup problem.  For decimal, the even/odd cases look
1000      * like this:
1001      *
1002      * Last   Round   Sticky
1003      * 6      5       0      => 6   // exactly halfway, return even digit.
1004      * 6      5       1      => 7   // a little bit more than halfway, round up.
1005      * 7      5       0      => 8   // exactly halfway, round up to even.
1006      * 7      5       1      => 8   // a little bit more than halfway, round up.
1007      * With analogous entries for other even and odd last-returned digits.
1008      *
1009      * However, decimal negative powers of 5 smaller than 0.5 are *not* exactly
1010      * representable as binary fraction.  In particular, 0.005 (the round limit
1011      * for a two-digit scale) and 0.0005 (the round limit for a three-digit
1012      * scale) are not representable. Therefore, for input values near these cases
1013      * the sticky bit is known to be set which reduces the rounding logic to:
1014      *
1015      * Last   Round   Sticky
1016      * 6      5       1      => 7   // a little bit more than halfway, round up.
1017      * 7      5       1      => 8   // a little bit more than halfway, round up.
1018      *
1019      * In other words, if the round digit is 5, the sticky bit is known to be
1020      * set.  If the round digit is something other than 5, the sticky bit is not
1021      * relevant.  Therefore, some of the logic about whether or not to increment
1022      * the destination *decimal* value can occur based on tests of *binary*
1023      * computations of the binary input number.
1024      */
1025 
1026     /**
1027      * Check validity of using fast-path for this instance. If fast-path is valid
1028      * for this instance, sets fast-path state as true and initializes fast-path
1029      * utility fields as needed.
1030      *
1031      * This method is supposed to be called rarely, otherwise that will break the
1032      * fast-path performance. That means avoiding frequent changes of the
1033      * properties of the instance, since for most properties, each time a change
1034      * happens, a call to this method is needed at the next format call.
1035      *
1036      * FAST-PATH RULES:
1037      *  Similar to the default DecimalFormat instantiation case.
1038      *  More precisely:
1039      *  - HALF_EVEN rounding mode,
1040      *  - isGroupingUsed() is true,
1041      *  - groupingSize of 3,
1042      *  - multiplier is 1,
1043      *  - Decimal separator not mandatory,
1044      *  - No use of exponential notation,
1045      *  - minimumIntegerDigits is exactly 1 and maximumIntegerDigits at least 10
1046      *  - For number of fractional digits, the exact values found in the default case:
1047      *     Currency : min = max = 2.
1048      *     Decimal  : min = 0. max = 3.
1049      *
1050      */
1051     private boolean checkAndSetFastPathStatus() {
1052 
1053         boolean fastPathWasOn = isFastPath;
1054 
1055         if ((roundingMode == RoundingMode.HALF_EVEN) &&
1056             (isGroupingUsed()) &&
1057             (groupingSize == 3) &&
1058             (multiplier == 1) &&
1059             (!decimalSeparatorAlwaysShown) &&
1060             (!useExponentialNotation)) {
1061 
1062             // The fast-path algorithm is semi-hardcoded against
1063             //  minimumIntegerDigits and maximumIntegerDigits.
1064             isFastPath = ((minimumIntegerDigits == 1) &&
1065                           (maximumIntegerDigits >= 10));
1066 
1067             // The fast-path algorithm is hardcoded against
1068             //  minimumFractionDigits and maximumFractionDigits.
1069             if (isFastPath) {
1070                 if (isCurrencyFormat) {
1071                     if ((minimumFractionDigits != 2) ||
1072                         (maximumFractionDigits != 2))
1073                         isFastPath = false;
1074                 } else if ((minimumFractionDigits != 0) ||
1075                            (maximumFractionDigits != 3))
1076                     isFastPath = false;
1077             }
1078         } else
1079             isFastPath = false;
1080 
1081         resetFastPathData(fastPathWasOn);
1082         fastPathCheckNeeded = false;
1083 
1084         /*
1085          * Returns true after successfully checking the fast path condition and
1086          * setting the fast path data. The return value is used by the
1087          * fastFormat() method to decide whether to call the resetFastPathData
1088          * method to reinitialize fast path data or is it already initialized
1089          * in this method.
1090          */
1091         return true;
1092     }
1093 
1094     private void resetFastPathData(boolean fastPathWasOn) {
1095         // Since some instance properties may have changed while still falling
1096         // in the fast-path case, we need to reinitialize fastPathData anyway.
1097         if (isFastPath) {
1098             // We need to instantiate fastPathData if not already done.
1099             if (fastPathData == null) {
1100                 fastPathData = new FastPathData();
1101             }
1102 
1103             // Sets up the locale specific constants used when formatting.
1104             // '0' is our default representation of zero.
1105             fastPathData.zeroDelta = symbols.getZeroDigit() - '0';
1106             fastPathData.groupingChar = symbols.getGroupingSeparator();
1107 
1108             // Sets up fractional constants related to currency/decimal pattern.
1109             fastPathData.fractionalMaxIntBound = (isCurrencyFormat)
1110                     ? 99 : 999;
1111             fastPathData.fractionalScaleFactor = (isCurrencyFormat)
1112                     ? 100.0d : 1000.0d;
1113 
1114             // Records the need for adding prefix or suffix
1115             fastPathData.positiveAffixesRequired
1116                     = !positivePrefix.isEmpty() || !positiveSuffix.isEmpty();
1117             fastPathData.negativeAffixesRequired
1118                     = !negativePrefix.isEmpty() || !negativeSuffix.isEmpty();
1119 
1120             // Creates a cached char container for result, with max possible size.
1121             int maxNbIntegralDigits = 10;
1122             int maxNbGroups = 3;
1123             int containerSize
1124                     = Math.max(positivePrefix.length(), negativePrefix.length())
1125                     + maxNbIntegralDigits + maxNbGroups + 1
1126                     + maximumFractionDigits
1127                     + Math.max(positiveSuffix.length(), negativeSuffix.length());
1128 
1129             fastPathData.fastPathContainer = new char[containerSize];
1130 
1131             // Sets up prefix and suffix char arrays constants.
1132             fastPathData.charsPositiveSuffix = positiveSuffix.toCharArray();
1133             fastPathData.charsNegativeSuffix = negativeSuffix.toCharArray();
1134             fastPathData.charsPositivePrefix = positivePrefix.toCharArray();
1135             fastPathData.charsNegativePrefix = negativePrefix.toCharArray();
1136 
1137             // Sets up fixed index positions for integral and fractional digits.
1138             // Sets up decimal point in cached result container.
1139             int longestPrefixLength
1140                     = Math.max(positivePrefix.length(),
1141                             negativePrefix.length());
1142             int decimalPointIndex
1143                     = maxNbIntegralDigits + maxNbGroups + longestPrefixLength;
1144 
1145             fastPathData.integralLastIndex = decimalPointIndex - 1;
1146             fastPathData.fractionalFirstIndex = decimalPointIndex + 1;
1147             fastPathData.fastPathContainer[decimalPointIndex]
1148                     = isCurrencyFormat
1149                             ? symbols.getMonetaryDecimalSeparator()
1150                             : symbols.getDecimalSeparator();
1151 
1152         } else if (fastPathWasOn) {
1153             // Previous state was fast-path and is no more.
1154             // Resets cached array constants.
1155             fastPathData.fastPathContainer = null;
1156             fastPathData.charsPositiveSuffix = null;
1157             fastPathData.charsNegativeSuffix = null;
1158             fastPathData.charsPositivePrefix = null;
1159             fastPathData.charsNegativePrefix = null;
1160         }
1161     }
1162 
1163     /**
1164      * Returns true if rounding-up must be done on {@code scaledFractionalPartAsInt},
1165      * false otherwise.
1166      *
1167      * This is a utility method that takes correct half-even rounding decision on
1168      * passed fractional value at the scaled decimal point (2 digits for currency
1169      * case and 3 for decimal case), when the approximated fractional part after
1170      * scaled decimal point is exactly 0.5d.  This is done by means of exact
1171      * calculations on the {@code fractionalPart} floating-point value.
1172      *
1173      * This method is supposed to be called by private {@code fastDoubleFormat}
1174      * method only.
1175      *
1176      * The algorithms used for the exact calculations are :
1177      *
1178      * The <b><i>FastTwoSum</i></b> algorithm, from T.J.Dekker, described in the
1179      * papers  "<i>A  Floating-Point   Technique  for  Extending  the  Available
1180      * Precision</i>"  by Dekker, and  in "<i>Adaptive  Precision Floating-Point
1181      * Arithmetic and Fast Robust Geometric Predicates</i>" from J.Shewchuk.
1182      *
1183      * A modified version of <b><i>Sum2S</i></b> cascaded summation described in
1184      * "<i>Accurate Sum and Dot Product</i>" from Takeshi Ogita and All.  As
1185      * Ogita says in this paper this is an equivalent of the Kahan-Babuska's
1186      * summation algorithm because we order the terms by magnitude before summing
1187      * them. For this reason we can use the <i>FastTwoSum</i> algorithm rather
1188      * than the more expensive Knuth's <i>TwoSum</i>.
1189      *
1190      * We do this to avoid a more expensive exact "<i>TwoProduct</i>" algorithm,
1191      * like those described in Shewchuk's paper above. See comments in the code
1192      * below.
1193      *
1194      * @param  fractionalPart The  fractional value  on which  we  take rounding
1195      * decision.
1196      * @param scaledFractionalPartAsInt The integral part of the scaled
1197      * fractional value.
1198      *
1199      * @return the decision that must be taken regarding half-even rounding.
1200      */
1201     private boolean exactRoundUp(double fractionalPart,
1202                                  int scaledFractionalPartAsInt) {
1203 
1204         /* exactRoundUp() method is called by fastDoubleFormat() only.
1205          * The precondition expected to be verified by the passed parameters is :
1206          * scaledFractionalPartAsInt ==
1207          *     (int) (fractionalPart * fastPathData.fractionalScaleFactor).
1208          * This is ensured by fastDoubleFormat() code.
1209          */
1210 
1211         /* We first calculate roundoff error made by fastDoubleFormat() on
1212          * the scaled fractional part. We do this with exact calculation on the
1213          * passed fractionalPart. Rounding decision will then be taken from roundoff.
1214          */
1215 
1216         /* ---- TwoProduct(fractionalPart, scale factor (i.e. 1000.0d or 100.0d)).
1217          *
1218          * The below is an optimized exact "TwoProduct" calculation of passed
1219          * fractional part with scale factor, using Ogita's Sum2S cascaded
1220          * summation adapted as Kahan-Babuska equivalent by using FastTwoSum
1221          * (much faster) rather than Knuth's TwoSum.
1222          *
1223          * We can do this because we order the summation from smallest to
1224          * greatest, so that FastTwoSum can be used without any additional error.
1225          *
1226          * The "TwoProduct" exact calculation needs 17 flops. We replace this by
1227          * a cascaded summation of FastTwoSum calculations, each involving an
1228          * exact multiply by a power of 2.
1229          *
1230          * Doing so saves overall 4 multiplications and 1 addition compared to
1231          * using traditional "TwoProduct".
1232          *
1233          * The scale factor is either 100 (currency case) or 1000 (decimal case).
1234          * - when 1000, we replace it by (1024 - 16 - 8) = 1000.
1235          * - when 100,  we replace it by (128  - 32 + 4) =  100.
1236          * Every multiplication by a power of 2 (1024, 128, 32, 16, 8, 4) is exact.
1237          *
1238          */
1239         double approxMax;    // Will always be positive.
1240         double approxMedium; // Will always be negative.
1241         double approxMin;
1242 
1243         double fastTwoSumApproximation = 0.0d;
1244         double fastTwoSumRoundOff = 0.0d;
1245         double bVirtual = 0.0d;
1246 
1247         if (isCurrencyFormat) {
1248             // Scale is 100 = 128 - 32 + 4.
1249             // Multiply by 2**n is a shift. No roundoff. No error.
1250             approxMax    = fractionalPart * 128.00d;
1251             approxMedium = - (fractionalPart * 32.00d);
1252             approxMin    = fractionalPart * 4.00d;
1253         } else {
1254             // Scale is 1000 = 1024 - 16 - 8.
1255             // Multiply by 2**n is a shift. No roundoff. No error.
1256             approxMax    = fractionalPart * 1024.00d;
1257             approxMedium = - (fractionalPart * 16.00d);
1258             approxMin    = - (fractionalPart * 8.00d);
1259         }
1260 
1261         // Shewchuk/Dekker's FastTwoSum(approxMedium, approxMin).
1262         assert(-approxMedium >= Math.abs(approxMin));
1263         fastTwoSumApproximation = approxMedium + approxMin;
1264         bVirtual = fastTwoSumApproximation - approxMedium;
1265         fastTwoSumRoundOff = approxMin - bVirtual;
1266         double approxS1 = fastTwoSumApproximation;
1267         double roundoffS1 = fastTwoSumRoundOff;
1268 
1269         // Shewchuk/Dekker's FastTwoSum(approxMax, approxS1);
1270         assert(approxMax >= Math.abs(approxS1));
1271         fastTwoSumApproximation = approxMax + approxS1;
1272         bVirtual = fastTwoSumApproximation - approxMax;
1273         fastTwoSumRoundOff = approxS1 - bVirtual;
1274         double roundoff1000 = fastTwoSumRoundOff;
1275         double approx1000 = fastTwoSumApproximation;
1276         double roundoffTotal = roundoffS1 + roundoff1000;
1277 
1278         // Shewchuk/Dekker's FastTwoSum(approx1000, roundoffTotal);
1279         assert(approx1000 >= Math.abs(roundoffTotal));
1280         fastTwoSumApproximation = approx1000 + roundoffTotal;
1281         bVirtual = fastTwoSumApproximation - approx1000;
1282 
1283         // Now we have got the roundoff for the scaled fractional
1284         double scaledFractionalRoundoff = roundoffTotal - bVirtual;
1285 
1286         // ---- TwoProduct(fractionalPart, scale (i.e. 1000.0d or 100.0d)) end.
1287 
1288         /* ---- Taking the rounding decision
1289          *
1290          * We take rounding decision based on roundoff and half-even rounding
1291          * rule.
1292          *
1293          * The above TwoProduct gives us the exact roundoff on the approximated
1294          * scaled fractional, and we know that this approximation is exactly
1295          * 0.5d, since that has already been tested by the caller
1296          * (fastDoubleFormat).
1297          *
1298          * Decision comes first from the sign of the calculated exact roundoff.
1299          * - Since being exact roundoff, it cannot be positive with a scaled
1300          *   fractional less than 0.5d, as well as negative with a scaled
1301          *   fractional greater than 0.5d. That leaves us with following 3 cases.
1302          * - positive, thus scaled fractional == 0.500....0fff ==> round-up.
1303          * - negative, thus scaled fractional == 0.499....9fff ==> don't round-up.
1304          * - is zero,  thus scaled fractioanl == 0.5 ==> half-even rounding applies :
1305          *    we round-up only if the integral part of the scaled fractional is odd.
1306          *
1307          */
1308         if (scaledFractionalRoundoff > 0.0) {
1309             return true;
1310         } else if (scaledFractionalRoundoff < 0.0) {
1311             return false;
1312         } else if ((scaledFractionalPartAsInt & 1) != 0) {
1313             return true;
1314         }
1315 
1316         return false;
1317 
1318         // ---- Taking the rounding decision end
1319     }
1320 
1321     /**
1322      * Collects integral digits from passed {@code number}, while setting
1323      * grouping chars as needed. Updates {@code firstUsedIndex} accordingly.
1324      *
1325      * Loops downward starting from {@code backwardIndex} position (inclusive).
1326      *
1327      * @param number  The int value from which we collect digits.
1328      * @param digitsBuffer The char array container where digits and grouping chars
1329      *  are stored.
1330      * @param backwardIndex the position from which we start storing digits in
1331      *  digitsBuffer.
1332      *
1333      */
1334     private void collectIntegralDigits(int number,
1335                                        char[] digitsBuffer,
1336                                        int backwardIndex) {
1337         int index = backwardIndex;
1338         int q;
1339         int r;
1340         while (number > 999) {
1341             // Generates 3 digits per iteration.
1342             q = number / 1000;
1343             r = number - (q << 10) + (q << 4) + (q << 3); // -1024 +16 +8 = 1000.
1344             number = q;
1345 
1346             digitsBuffer[index--] = DigitArrays.DigitOnes1000[r];
1347             digitsBuffer[index--] = DigitArrays.DigitTens1000[r];
1348             digitsBuffer[index--] = DigitArrays.DigitHundreds1000[r];
1349             digitsBuffer[index--] = fastPathData.groupingChar;
1350         }
1351 
1352         // Collects last 3 or less digits.
1353         digitsBuffer[index] = DigitArrays.DigitOnes1000[number];
1354         if (number > 9) {
1355             digitsBuffer[--index]  = DigitArrays.DigitTens1000[number];
1356             if (number > 99)
1357                 digitsBuffer[--index]   = DigitArrays.DigitHundreds1000[number];
1358         }
1359 
1360         fastPathData.firstUsedIndex = index;
1361     }
1362 
1363     /**
1364      * Collects the 2 (currency) or 3 (decimal) fractional digits from passed
1365      * {@code number}, starting at {@code startIndex} position
1366      * inclusive.  There is no punctuation to set here (no grouping chars).
1367      * Updates {@code fastPathData.lastFreeIndex} accordingly.
1368      *
1369      *
1370      * @param number  The int value from which we collect digits.
1371      * @param digitsBuffer The char array container where digits are stored.
1372      * @param startIndex the position from which we start storing digits in
1373      *  digitsBuffer.
1374      *
1375      */
1376     private void collectFractionalDigits(int number,
1377                                          char[] digitsBuffer,
1378                                          int startIndex) {
1379         int index = startIndex;
1380 
1381         char digitOnes = DigitArrays.DigitOnes1000[number];
1382         char digitTens = DigitArrays.DigitTens1000[number];
1383 
1384         if (isCurrencyFormat) {
1385             // Currency case. Always collects fractional digits.
1386             digitsBuffer[index++] = digitTens;
1387             digitsBuffer[index++] = digitOnes;
1388         } else if (number != 0) {
1389             // Decimal case. Hundreds will always be collected
1390             digitsBuffer[index++] = DigitArrays.DigitHundreds1000[number];
1391 
1392             // Ending zeros won't be collected.
1393             if (digitOnes != '0') {
1394                 digitsBuffer[index++] = digitTens;
1395                 digitsBuffer[index++] = digitOnes;
1396             } else if (digitTens != '0')
1397                 digitsBuffer[index++] = digitTens;
1398 
1399         } else
1400             // This is decimal pattern and fractional part is zero.
1401             // We must remove decimal point from result.
1402             index--;
1403 
1404         fastPathData.lastFreeIndex = index;
1405     }
1406 
1407     /**
1408      * Internal utility.
1409      * Adds the passed {@code prefix} and {@code suffix} to {@code container}.
1410      *
1411      * @param container  Char array container which to prepend/append the
1412      *  prefix/suffix.
1413      * @param prefix     Char sequence to prepend as a prefix.
1414      * @param suffix     Char sequence to append as a suffix.
1415      *
1416      */
1417     //    private void addAffixes(boolean isNegative, char[] container) {
1418     private void addAffixes(char[] container, char[] prefix, char[] suffix) {
1419 
1420         // We add affixes only if needed (affix length > 0).
1421         int pl = prefix.length;
1422         int sl = suffix.length;
1423         if (pl != 0) prependPrefix(prefix, pl, container);
1424         if (sl != 0) appendSuffix(suffix, sl, container);
1425 
1426     }
1427 
1428     /**
1429      * Prepends the passed {@code prefix} chars to given result
1430      * {@code container}.  Updates {@code fastPathData.firstUsedIndex}
1431      * accordingly.
1432      *
1433      * @param prefix The prefix characters to prepend to result.
1434      * @param len The number of chars to prepend.
1435      * @param container Char array container which to prepend the prefix
1436      */
1437     private void prependPrefix(char[] prefix,
1438                                int len,
1439                                char[] container) {
1440 
1441         fastPathData.firstUsedIndex -= len;
1442         int startIndex = fastPathData.firstUsedIndex;
1443 
1444         // If prefix to prepend is only 1 char long, just assigns this char.
1445         // If prefix is less or equal 4, we use a dedicated algorithm that
1446         //  has shown to run faster than System.arraycopy.
1447         // If more than 4, we use System.arraycopy.
1448         if (len == 1)
1449             container[startIndex] = prefix[0];
1450         else if (len <= 4) {
1451             int dstLower = startIndex;
1452             int dstUpper = dstLower + len - 1;
1453             int srcUpper = len - 1;
1454             container[dstLower] = prefix[0];
1455             container[dstUpper] = prefix[srcUpper];
1456 
1457             if (len > 2)
1458                 container[++dstLower] = prefix[1];
1459             if (len == 4)
1460                 container[--dstUpper] = prefix[2];
1461         } else
1462             System.arraycopy(prefix, 0, container, startIndex, len);
1463     }
1464 
1465     /**
1466      * Appends the passed {@code suffix} chars to given result
1467      * {@code container}.  Updates {@code fastPathData.lastFreeIndex}
1468      * accordingly.
1469      *
1470      * @param suffix The suffix characters to append to result.
1471      * @param len The number of chars to append.
1472      * @param container Char array container which to append the suffix
1473      */
1474     private void appendSuffix(char[] suffix,
1475                               int len,
1476                               char[] container) {
1477 
1478         int startIndex = fastPathData.lastFreeIndex;
1479 
1480         // If suffix to append is only 1 char long, just assigns this char.
1481         // If suffix is less or equal 4, we use a dedicated algorithm that
1482         //  has shown to run faster than System.arraycopy.
1483         // If more than 4, we use System.arraycopy.
1484         if (len == 1)
1485             container[startIndex] = suffix[0];
1486         else if (len <= 4) {
1487             int dstLower = startIndex;
1488             int dstUpper = dstLower + len - 1;
1489             int srcUpper = len - 1;
1490             container[dstLower] = suffix[0];
1491             container[dstUpper] = suffix[srcUpper];
1492 
1493             if (len > 2)
1494                 container[++dstLower] = suffix[1];
1495             if (len == 4)
1496                 container[--dstUpper] = suffix[2];
1497         } else
1498             System.arraycopy(suffix, 0, container, startIndex, len);
1499 
1500         fastPathData.lastFreeIndex += len;
1501     }
1502 
1503     /**
1504      * Converts digit chars from {@code digitsBuffer} to current locale.
1505      *
1506      * Must be called before adding affixes since we refer to
1507      * {@code fastPathData.firstUsedIndex} and {@code fastPathData.lastFreeIndex},
1508      * and do not support affixes (for speed reason).
1509      *
1510      * We loop backward starting from last used index in {@code fastPathData}.
1511      *
1512      * @param digitsBuffer The char array container where the digits are stored.
1513      */
1514     private void localizeDigits(char[] digitsBuffer) {
1515 
1516         // We will localize only the digits, using the groupingSize,
1517         // and taking into account fractional part.
1518 
1519         // First take into account fractional part.
1520         int digitsCounter =
1521             fastPathData.lastFreeIndex - fastPathData.fractionalFirstIndex;
1522 
1523         // The case when there is no fractional digits.
1524         if (digitsCounter < 0)
1525             digitsCounter = groupingSize;
1526 
1527         // Only the digits remains to localize.
1528         for (int cursor = fastPathData.lastFreeIndex - 1;
1529              cursor >= fastPathData.firstUsedIndex;
1530              cursor--) {
1531             if (digitsCounter != 0) {
1532                 // This is a digit char, we must localize it.
1533                 digitsBuffer[cursor] += fastPathData.zeroDelta;
1534                 digitsCounter--;
1535             } else {
1536                 // Decimal separator or grouping char. Reinit counter only.
1537                 digitsCounter = groupingSize;
1538             }
1539         }
1540     }
1541 
1542     /**
1543      * This is the main entry point for the fast-path format algorithm.
1544      *
1545      * At this point we are sure to be in the expected conditions to run it.
1546      * This algorithm builds the formatted result and puts it in the dedicated
1547      * {@code fastPathData.fastPathContainer}.
1548      *
1549      * @param d the double value to be formatted.
1550      * @param negative Flag precising if {@code d} is negative.
1551      */
1552     private void fastDoubleFormat(double d,
1553                                   boolean negative) {
1554 
1555         char[] container = fastPathData.fastPathContainer;
1556 
1557         /*
1558          * The principle of the algorithm is to :
1559          * - Break the passed double into its integral and fractional parts
1560          *    converted into integers.
1561          * - Then decide if rounding up must be applied or not by following
1562          *    the half-even rounding rule, first using approximated scaled
1563          *    fractional part.
1564          * - For the difficult cases (approximated scaled fractional part
1565          *    being exactly 0.5d), we refine the rounding decision by calling
1566          *    exactRoundUp utility method that both calculates the exact roundoff
1567          *    on the approximation and takes correct rounding decision.
1568          * - We round-up the fractional part if needed, possibly propagating the
1569          *    rounding to integral part if we meet a "all-nine" case for the
1570          *    scaled fractional part.
1571          * - We then collect digits from the resulting integral and fractional
1572          *   parts, also setting the required grouping chars on the fly.
1573          * - Then we localize the collected digits if needed, and
1574          * - Finally prepend/append prefix/suffix if any is needed.
1575          */
1576 
1577         // Exact integral part of d.
1578         int integralPartAsInt = (int) d;
1579 
1580         // Exact fractional part of d (since we subtract it's integral part).
1581         double exactFractionalPart = d - (double) integralPartAsInt;
1582 
1583         // Approximated scaled fractional part of d (due to multiplication).
1584         double scaledFractional =
1585             exactFractionalPart * fastPathData.fractionalScaleFactor;
1586 
1587         // Exact integral part of scaled fractional above.
1588         int fractionalPartAsInt = (int) scaledFractional;
1589 
1590         // Exact fractional part of scaled fractional above.
1591         scaledFractional = scaledFractional - (double) fractionalPartAsInt;
1592 
1593         // Only when scaledFractional is exactly 0.5d do we have to do exact
1594         // calculations and take fine-grained rounding decision, since
1595         // approximated results above may lead to incorrect decision.
1596         // Otherwise comparing against 0.5d (strictly greater or less) is ok.
1597         boolean roundItUp = false;
1598         if (scaledFractional >= 0.5d) {
1599             if (scaledFractional == 0.5d)
1600                 // Rounding need fine-grained decision.
1601                 roundItUp = exactRoundUp(exactFractionalPart, fractionalPartAsInt);
1602             else
1603                 roundItUp = true;
1604 
1605             if (roundItUp) {
1606                 // Rounds up both fractional part (and also integral if needed).
1607                 if (fractionalPartAsInt < fastPathData.fractionalMaxIntBound) {
1608                     fractionalPartAsInt++;
1609                 } else {
1610                     // Propagates rounding to integral part since "all nines" case.
1611                     fractionalPartAsInt = 0;
1612                     integralPartAsInt++;
1613                 }
1614             }
1615         }
1616 
1617         // Collecting digits.
1618         collectFractionalDigits(fractionalPartAsInt, container,
1619                                 fastPathData.fractionalFirstIndex);
1620         collectIntegralDigits(integralPartAsInt, container,
1621                               fastPathData.integralLastIndex);
1622 
1623         // Localizing digits.
1624         if (fastPathData.zeroDelta != 0)
1625             localizeDigits(container);
1626 
1627         // Adding prefix and suffix.
1628         if (negative) {
1629             if (fastPathData.negativeAffixesRequired)
1630                 addAffixes(container,
1631                            fastPathData.charsNegativePrefix,
1632                            fastPathData.charsNegativeSuffix);
1633         } else if (fastPathData.positiveAffixesRequired)
1634             addAffixes(container,
1635                        fastPathData.charsPositivePrefix,
1636                        fastPathData.charsPositiveSuffix);
1637     }
1638 
1639     /**
1640      * A fast-path shortcut of format(double) to be called by NumberFormat, or by
1641      * format(double, ...) public methods.
1642      *
1643      * If instance can be applied fast-path and passed double is not NaN or
1644      * Infinity, is in the integer range, we call {@code fastDoubleFormat}
1645      * after changing {@code d} to its positive value if necessary.
1646      *
1647      * Otherwise returns null by convention since fast-path can't be exercized.
1648      *
1649      * @param d The double value to be formatted
1650      *
1651      * @return the formatted result for {@code d} as a string.
1652      */
1653     String fastFormat(double d) {
1654         boolean isDataSet = false;
1655         // (Re-)Evaluates fast-path status if needed.
1656         if (fastPathCheckNeeded) {
1657             isDataSet = checkAndSetFastPathStatus();
1658         }
1659 
1660         if (!isFastPath )
1661             // DecimalFormat instance is not in a fast-path state.
1662             return null;
1663 
1664         if (!Double.isFinite(d))
1665             // Should not use fast-path for Infinity and NaN.
1666             return null;
1667 
1668         // Extracts and records sign of double value, possibly changing it
1669         // to a positive one, before calling fastDoubleFormat().
1670         boolean negative = false;
1671         if (d < 0.0d) {
1672             negative = true;
1673             d = -d;
1674         } else if (d == 0.0d) {
1675             negative = (Math.copySign(1.0d, d) == -1.0d);
1676             d = +0.0d;
1677         }
1678 
1679         if (d > MAX_INT_AS_DOUBLE)
1680             // Filters out values that are outside expected fast-path range
1681             return null;
1682         else {
1683             if (!isDataSet) {
1684                 /*
1685                  * If the fast path data is not set through
1686                  * checkAndSetFastPathStatus() and fulfil the
1687                  * fast path conditions then reset the data
1688                  * directly through resetFastPathData()
1689                  */
1690                 resetFastPathData(isFastPath);
1691             }
1692             fastDoubleFormat(d, negative);
1693 
1694         }
1695 
1696 
1697         // Returns a new string from updated fastPathContainer.
1698         return new String(fastPathData.fastPathContainer,
1699                           fastPathData.firstUsedIndex,
1700                           fastPathData.lastFreeIndex - fastPathData.firstUsedIndex);
1701 
1702     }
1703 
1704     /**
1705      * Sets the {@code DigitList} used by this {@code DecimalFormat}
1706      * instance.
1707      * @param number the number to format
1708      * @param isNegative true, if the number is negative; false otherwise
1709      * @param maxDigits the max digits
1710      */
1711     void setDigitList(Number number, boolean isNegative, int maxDigits) {
1712 
1713         if (number instanceof Double) {
1714             digitList.set(isNegative, (Double) number, maxDigits, true);
1715         } else if (number instanceof BigDecimal) {
1716             digitList.set(isNegative, (BigDecimal) number, maxDigits, true);
1717         } else if (number instanceof Long) {
1718             digitList.set(isNegative, (Long) number, maxDigits);
1719         } else if (number instanceof BigInteger) {
1720             digitList.set(isNegative, (BigInteger) number, maxDigits);
1721         }
1722     }
1723 
1724     // ======== End fast-path formating logic for double =========================
1725 
1726     /**
1727      * Complete the formatting of a finite number.  On entry, the digitList must
1728      * be filled in with the correct digits.
1729      */
1730     private StringBuffer subformat(StringBuffer result, FieldDelegate delegate,
1731             boolean isNegative, boolean isInteger,
1732             int maxIntDigits, int minIntDigits,
1733             int maxFraDigits, int minFraDigits) {
1734 
1735         // Process prefix
1736         if (isNegative) {
1737             append(result, negativePrefix, delegate,
1738                     getNegativePrefixFieldPositions(), Field.SIGN);
1739         } else {
1740             append(result, positivePrefix, delegate,
1741                     getPositivePrefixFieldPositions(), Field.SIGN);
1742         }
1743 
1744         // Process number
1745         subformatNumber(result, delegate, isNegative, isInteger,
1746                 maxIntDigits, minIntDigits, maxFraDigits, minFraDigits);
1747 
1748         // Process suffix
1749         if (isNegative) {
1750             append(result, negativeSuffix, delegate,
1751                     getNegativeSuffixFieldPositions(), Field.SIGN);
1752         } else {
1753             append(result, positiveSuffix, delegate,
1754                     getPositiveSuffixFieldPositions(), Field.SIGN);
1755         }
1756 
1757         return result;
1758     }
1759 
1760     /**
1761      * Subformats number part using the {@code DigitList} of this
1762      * {@code DecimalFormat} instance.
1763      * @param result where the text is to be appended
1764      * @param delegate notified of the location of sub fields
1765      * @param isNegative true, if the number is negative; false otherwise
1766      * @param isInteger true, if the number is an integer; false otherwise
1767      * @param maxIntDigits maximum integer digits
1768      * @param minIntDigits minimum integer digits
1769      * @param maxFraDigits maximum fraction digits
1770      * @param minFraDigits minimum fraction digits
1771      */
1772     void subformatNumber(StringBuffer result, FieldDelegate delegate,
1773             boolean isNegative, boolean isInteger,
1774             int maxIntDigits, int minIntDigits,
1775             int maxFraDigits, int minFraDigits) {
1776 
1777         char grouping = symbols.getGroupingSeparator();
1778         char zero = symbols.getZeroDigit();
1779         int zeroDelta = zero - '0'; // '0' is the DigitList representation of zero
1780 
1781         char decimal = isCurrencyFormat ?
1782                 symbols.getMonetaryDecimalSeparator() :
1783                 symbols.getDecimalSeparator();
1784 
1785         /* Per bug 4147706, DecimalFormat must respect the sign of numbers which
1786          * format as zero.  This allows sensible computations and preserves
1787          * relations such as signum(1/x) = signum(x), where x is +Infinity or
1788          * -Infinity.  Prior to this fix, we always formatted zero values as if
1789          * they were positive.  Liu 7/6/98.
1790          */
1791         if (digitList.isZero()) {
1792             digitList.decimalAt = 0; // Normalize
1793         }
1794 
1795         if (useExponentialNotation) {
1796             int iFieldStart = result.length();
1797             int iFieldEnd = -1;
1798             int fFieldStart = -1;
1799 
1800             // Minimum integer digits are handled in exponential format by
1801             // adjusting the exponent.  For example, 0.01234 with 3 minimum
1802             // integer digits is "123.4E-4".
1803             // Maximum integer digits are interpreted as indicating the
1804             // repeating range.  This is useful for engineering notation, in
1805             // which the exponent is restricted to a multiple of 3.  For
1806             // example, 0.01234 with 3 maximum integer digits is "12.34e-3".
1807             // If maximum integer digits are > 1 and are larger than
1808             // minimum integer digits, then minimum integer digits are
1809             // ignored.
1810             int exponent = digitList.decimalAt;
1811             int repeat = maxIntDigits;
1812             int minimumIntegerDigits = minIntDigits;
1813             if (repeat > 1 && repeat > minIntDigits) {
1814                 // A repeating range is defined; adjust to it as follows.
1815                 // If repeat == 3, we have 6,5,4=>3; 3,2,1=>0; 0,-1,-2=>-3;
1816                 // -3,-4,-5=>-6, etc. This takes into account that the
1817                 // exponent we have here is off by one from what we expect;
1818                 // it is for the format 0.MMMMMx10^n.
1819                 if (exponent >= 1) {
1820                     exponent = ((exponent - 1) / repeat) * repeat;
1821                 } else {
1822                     // integer division rounds towards 0
1823                     exponent = ((exponent - repeat) / repeat) * repeat;
1824                 }
1825                 minimumIntegerDigits = 1;
1826             } else {
1827                 // No repeating range is defined; use minimum integer digits.
1828                 exponent -= minimumIntegerDigits;
1829             }
1830 
1831             // We now output a minimum number of digits, and more if there
1832             // are more digits, up to the maximum number of digits.  We
1833             // place the decimal point after the "integer" digits, which
1834             // are the first (decimalAt - exponent) digits.
1835             int minimumDigits = minIntDigits + minFraDigits;
1836             if (minimumDigits < 0) {    // overflow?
1837                 minimumDigits = Integer.MAX_VALUE;
1838             }
1839 
1840             // The number of integer digits is handled specially if the number
1841             // is zero, since then there may be no digits.
1842             int integerDigits = digitList.isZero() ? minimumIntegerDigits :
1843                     digitList.decimalAt - exponent;
1844             if (minimumDigits < integerDigits) {
1845                 minimumDigits = integerDigits;
1846             }
1847             int totalDigits = digitList.count;
1848             if (minimumDigits > totalDigits) {
1849                 totalDigits = minimumDigits;
1850             }
1851             boolean addedDecimalSeparator = false;
1852 
1853             for (int i=0; i<totalDigits; ++i) {
1854                 if (i == integerDigits) {
1855                     // Record field information for caller.
1856                     iFieldEnd = result.length();
1857 
1858                     result.append(decimal);
1859                     addedDecimalSeparator = true;
1860 
1861                     // Record field information for caller.
1862                     fFieldStart = result.length();
1863                 }
1864                 result.append((i < digitList.count) ?
1865                         (char)(digitList.digits[i] + zeroDelta) :
1866                         zero);
1867             }
1868 
1869             if (decimalSeparatorAlwaysShown && totalDigits == integerDigits) {
1870                 // Record field information for caller.
1871                 iFieldEnd = result.length();
1872 
1873                 result.append(decimal);
1874                 addedDecimalSeparator = true;
1875 
1876                 // Record field information for caller.
1877                 fFieldStart = result.length();
1878             }
1879 
1880             // Record field information
1881             if (iFieldEnd == -1) {
1882                 iFieldEnd = result.length();
1883             }
1884             delegate.formatted(INTEGER_FIELD, Field.INTEGER, Field.INTEGER,
1885                     iFieldStart, iFieldEnd, result);
1886             if (addedDecimalSeparator) {
1887                 delegate.formatted(Field.DECIMAL_SEPARATOR,
1888                         Field.DECIMAL_SEPARATOR,
1889                         iFieldEnd, fFieldStart, result);
1890             }
1891             if (fFieldStart == -1) {
1892                 fFieldStart = result.length();
1893             }
1894             delegate.formatted(FRACTION_FIELD, Field.FRACTION, Field.FRACTION,
1895                     fFieldStart, result.length(), result);
1896 
1897             // The exponent is output using the pattern-specified minimum
1898             // exponent digits.  There is no maximum limit to the exponent
1899             // digits, since truncating the exponent would result in an
1900             // unacceptable inaccuracy.
1901             int fieldStart = result.length();
1902 
1903             result.append(symbols.getExponentSeparator());
1904 
1905             delegate.formatted(Field.EXPONENT_SYMBOL, Field.EXPONENT_SYMBOL,
1906                     fieldStart, result.length(), result);
1907 
1908             // For zero values, we force the exponent to zero.  We
1909             // must do this here, and not earlier, because the value
1910             // is used to determine integer digit count above.
1911             if (digitList.isZero()) {
1912                 exponent = 0;
1913             }
1914 
1915             boolean negativeExponent = exponent < 0;
1916             if (negativeExponent) {
1917                 exponent = -exponent;
1918                 fieldStart = result.length();
1919                 result.append(symbols.getMinusSignText());
1920                 delegate.formatted(Field.EXPONENT_SIGN, Field.EXPONENT_SIGN,
1921                         fieldStart, result.length(), result);
1922             }
1923             digitList.set(negativeExponent, exponent);
1924 
1925             int eFieldStart = result.length();
1926 
1927             for (int i=digitList.decimalAt; i<minExponentDigits; ++i) {
1928                 result.append(zero);
1929             }
1930             for (int i=0; i<digitList.decimalAt; ++i) {
1931                 result.append((i < digitList.count) ?
1932                         (char)(digitList.digits[i] + zeroDelta) : zero);
1933             }
1934             delegate.formatted(Field.EXPONENT, Field.EXPONENT, eFieldStart,
1935                     result.length(), result);
1936         } else {
1937             int iFieldStart = result.length();
1938 
1939             // Output the integer portion.  Here 'count' is the total
1940             // number of integer digits we will display, including both
1941             // leading zeros required to satisfy getMinimumIntegerDigits,
1942             // and actual digits present in the number.
1943             int count = minIntDigits;
1944             int digitIndex = 0; // Index into digitList.fDigits[]
1945             if (digitList.decimalAt > 0 && count < digitList.decimalAt) {
1946                 count = digitList.decimalAt;
1947             }
1948 
1949             // Handle the case where getMaximumIntegerDigits() is smaller
1950             // than the real number of integer digits.  If this is so, we
1951             // output the least significant max integer digits.  For example,
1952             // the value 1997 printed with 2 max integer digits is just "97".
1953             if (count > maxIntDigits) {
1954                 count = maxIntDigits;
1955                 digitIndex = digitList.decimalAt - count;
1956             }
1957 
1958             int sizeBeforeIntegerPart = result.length();
1959             for (int i=count-1; i>=0; --i) {
1960                 if (i < digitList.decimalAt && digitIndex < digitList.count) {
1961                     // Output a real digit
1962                     result.append((char)(digitList.digits[digitIndex++] + zeroDelta));
1963                 } else {
1964                     // Output a leading zero
1965                     result.append(zero);
1966                 }
1967 
1968                 // Output grouping separator if necessary.  Don't output a
1969                 // grouping separator if i==0 though; that's at the end of
1970                 // the integer part.
1971                 if (isGroupingUsed() && i>0 && (groupingSize != 0) &&
1972                         (i % groupingSize == 0)) {
1973                     int gStart = result.length();
1974                     result.append(grouping);
1975                     delegate.formatted(Field.GROUPING_SEPARATOR,
1976                             Field.GROUPING_SEPARATOR, gStart,
1977                             result.length(), result);
1978                 }
1979             }
1980 
1981             // Determine whether or not there are any printable fractional
1982             // digits.  If we've used up the digits we know there aren't.
1983             boolean fractionPresent = (minFraDigits > 0) ||
1984                     (!isInteger && digitIndex < digitList.count);
1985 
1986             // If there is no fraction present, and we haven't printed any
1987             // integer digits, then print a zero.  Otherwise we won't print
1988             // _any_ digits, and we won't be able to parse this string.
1989             if (!fractionPresent && result.length() == sizeBeforeIntegerPart) {
1990                 result.append(zero);
1991             }
1992 
1993             delegate.formatted(INTEGER_FIELD, Field.INTEGER, Field.INTEGER,
1994                     iFieldStart, result.length(), result);
1995 
1996             // Output the decimal separator if we always do so.
1997             int sStart = result.length();
1998             if (decimalSeparatorAlwaysShown || fractionPresent) {
1999                 result.append(decimal);
2000             }
2001 
2002             if (sStart != result.length()) {
2003                 delegate.formatted(Field.DECIMAL_SEPARATOR,
2004                         Field.DECIMAL_SEPARATOR,
2005                         sStart, result.length(), result);
2006             }
2007             int fFieldStart = result.length();
2008 
2009             for (int i=0; i < maxFraDigits; ++i) {
2010                 // Here is where we escape from the loop.  We escape if we've
2011                 // output the maximum fraction digits (specified in the for
2012                 // expression above).
2013                 // We also stop when we've output the minimum digits and either:
2014                 // we have an integer, so there is no fractional stuff to
2015                 // display, or we're out of significant digits.
2016                 if (i >= minFraDigits &&
2017                         (isInteger || digitIndex >= digitList.count)) {
2018                     break;
2019                 }
2020 
2021                 // Output leading fractional zeros. These are zeros that come
2022                 // after the decimal but before any significant digits. These
2023                 // are only output if abs(number being formatted) < 1.0.
2024                 if (-1-i > (digitList.decimalAt-1)) {
2025                     result.append(zero);
2026                     continue;
2027                 }
2028 
2029                 // Output a digit, if we have any precision left, or a
2030                 // zero if we don't.  We don't want to output noise digits.
2031                 if (!isInteger && digitIndex < digitList.count) {
2032                     result.append((char)(digitList.digits[digitIndex++] + zeroDelta));
2033                 } else {
2034                     result.append(zero);
2035                 }
2036             }
2037 
2038             // Record field information for caller.
2039             delegate.formatted(FRACTION_FIELD, Field.FRACTION, Field.FRACTION,
2040                     fFieldStart, result.length(), result);
2041         }
2042     }
2043 
2044     /**
2045      * Appends the String {@code string} to {@code result}.
2046      * {@code delegate} is notified of all  the
2047      * {@code FieldPosition}s in {@code positions}.
2048      * <p>
2049      * If one of the {@code FieldPosition}s in {@code positions}
2050      * identifies a {@code SIGN} attribute, it is mapped to
2051      * {@code signAttribute}. This is used
2052      * to map the {@code SIGN} attribute to the {@code EXPONENT}
2053      * attribute as necessary.
2054      * <p>
2055      * This is used by {@code subformat} to add the prefix/suffix.
2056      */
2057     private void append(StringBuffer result, String string,
2058                         FieldDelegate delegate,
2059                         FieldPosition[] positions,
2060                         Format.Field signAttribute) {
2061         int start = result.length();
2062 
2063         if (!string.isEmpty()) {
2064             result.append(string);
2065             for (int counter = 0, max = positions.length; counter < max;
2066                  counter++) {
2067                 FieldPosition fp = positions[counter];
2068                 Format.Field attribute = fp.getFieldAttribute();
2069 
2070                 if (attribute == Field.SIGN) {
2071                     attribute = signAttribute;
2072                 }
2073                 delegate.formatted(attribute, attribute,
2074                                    start + fp.getBeginIndex(),
2075                                    start + fp.getEndIndex(), result);
2076             }
2077         }
2078     }
2079 
2080     /**
2081      * Parses text from a string to produce a {@code Number}.
2082      * <p>
2083      * The method attempts to parse text starting at the index given by
2084      * {@code pos}.
2085      * If parsing succeeds, then the index of {@code pos} is updated
2086      * to the index after the last character used (parsing does not necessarily
2087      * use all characters up to the end of the string), and the parsed
2088      * number is returned. The updated {@code pos} can be used to
2089      * indicate the starting point for the next call to this method.
2090      * If an error occurs, then the index of {@code pos} is not
2091      * changed, the error index of {@code pos} is set to the index of
2092      * the character where the error occurred, and null is returned.
2093      * <p>
2094      * The subclass returned depends on the value of {@link #isParseBigDecimal}
2095      * as well as on the string being parsed.
2096      * <ul>
2097      *   <li>If {@code isParseBigDecimal()} is false (the default),
2098      *       most integer values are returned as {@code Long}
2099      *       objects, no matter how they are written: {@code "17"} and
2100      *       {@code "17.000"} both parse to {@code Long(17)}.
2101      *       Values that cannot fit into a {@code Long} are returned as
2102      *       {@code Double}s. This includes values with a fractional part,
2103      *       infinite values, {@code NaN}, and the value -0.0.
2104      *       {@code DecimalFormat} does <em>not</em> decide whether to
2105      *       return a {@code Double} or a {@code Long} based on the
2106      *       presence of a decimal separator in the source string. Doing so
2107      *       would prevent integers that overflow the mantissa of a double,
2108      *       such as {@code "-9,223,372,036,854,775,808.00"}, from being
2109      *       parsed accurately.
2110      *       <p>
2111      *       Callers may use the {@code Number} methods
2112      *       {@code doubleValue}, {@code longValue}, etc., to obtain
2113      *       the type they want.
2114      *   <li>If {@code isParseBigDecimal()} is true, values are returned
2115      *       as {@code BigDecimal} objects. The values are the ones
2116      *       constructed by {@link java.math.BigDecimal#BigDecimal(String)}
2117      *       for corresponding strings in locale-independent format. The
2118      *       special cases negative and positive infinity and NaN are returned
2119      *       as {@code Double} instances holding the values of the
2120      *       corresponding {@code Double} constants.
2121      * </ul>
2122      * <p>
2123      * {@code DecimalFormat} parses all Unicode characters that represent
2124      * decimal digits, as defined by {@code Character.digit()}. In
2125      * addition, {@code DecimalFormat} also recognizes as digits the ten
2126      * consecutive characters starting with the localized zero digit defined in
2127      * the {@code DecimalFormatSymbols} object.
2128      *
2129      * @param text the string to be parsed
2130      * @param pos  A {@code ParsePosition} object with index and error
2131      *             index information as described above.
2132      * @return     the parsed value, or {@code null} if the parse fails
2133      * @exception  NullPointerException if {@code text} or
2134      *             {@code pos} is null.
2135      */
2136     @Override
2137     public Number parse(String text, ParsePosition pos) {
2138         // special case NaN
2139         if (text.regionMatches(pos.index, symbols.getNaN(), 0, symbols.getNaN().length())) {
2140             pos.index = pos.index + symbols.getNaN().length();
2141             return Double.valueOf(Double.NaN);
2142         }
2143 
2144         boolean[] status = new boolean[STATUS_LENGTH];
2145         if (!subparse(text, pos, positivePrefix, negativePrefix, digitList, false, status)) {
2146             return null;
2147         }
2148 
2149         // special case INFINITY
2150         if (status[STATUS_INFINITE]) {
2151             if (status[STATUS_POSITIVE] == (multiplier >= 0)) {
2152                 return Double.valueOf(Double.POSITIVE_INFINITY);
2153             } else {
2154                 return Double.valueOf(Double.NEGATIVE_INFINITY);
2155             }
2156         }
2157 
2158         if (multiplier == 0) {
2159             if (digitList.isZero()) {
2160                 return Double.valueOf(Double.NaN);
2161             } else if (status[STATUS_POSITIVE]) {
2162                 return Double.valueOf(Double.POSITIVE_INFINITY);
2163             } else {
2164                 return Double.valueOf(Double.NEGATIVE_INFINITY);
2165             }
2166         }
2167 
2168         if (isParseBigDecimal()) {
2169             BigDecimal bigDecimalResult = digitList.getBigDecimal();
2170 
2171             if (multiplier != 1) {
2172                 try {
2173                     bigDecimalResult = bigDecimalResult.divide(getBigDecimalMultiplier());
2174                 }
2175                 catch (ArithmeticException e) {  // non-terminating decimal expansion
2176                     bigDecimalResult = bigDecimalResult.divide(getBigDecimalMultiplier(), roundingMode);
2177                 }
2178             }
2179 
2180             if (!status[STATUS_POSITIVE]) {
2181                 bigDecimalResult = bigDecimalResult.negate();
2182             }
2183             return bigDecimalResult;
2184         } else {
2185             boolean gotDouble = true;
2186             boolean gotLongMinimum = false;
2187             double  doubleResult = 0.0;
2188             long    longResult = 0;
2189 
2190             // Finally, have DigitList parse the digits into a value.
2191             if (digitList.fitsIntoLong(status[STATUS_POSITIVE], isParseIntegerOnly())) {
2192                 gotDouble = false;
2193                 longResult = digitList.getLong();
2194                 if (longResult < 0) {  // got Long.MIN_VALUE
2195                     gotLongMinimum = true;
2196                 }
2197             } else {
2198                 doubleResult = digitList.getDouble();
2199             }
2200 
2201             // Divide by multiplier. We have to be careful here not to do
2202             // unneeded conversions between double and long.
2203             if (multiplier != 1) {
2204                 if (gotDouble) {
2205                     doubleResult /= multiplier;
2206                 } else {
2207                     // Avoid converting to double if we can
2208                     if (longResult % multiplier == 0) {
2209                         longResult /= multiplier;
2210                     } else {
2211                         doubleResult = ((double)longResult) / multiplier;
2212                         gotDouble = true;
2213                     }
2214                 }
2215             }
2216 
2217             if (!status[STATUS_POSITIVE] && !gotLongMinimum) {
2218                 doubleResult = -doubleResult;
2219                 longResult = -longResult;
2220             }
2221 
2222             // At this point, if we divided the result by the multiplier, the
2223             // result may fit into a long.  We check for this case and return
2224             // a long if possible.
2225             // We must do this AFTER applying the negative (if appropriate)
2226             // in order to handle the case of LONG_MIN; otherwise, if we do
2227             // this with a positive value -LONG_MIN, the double is > 0, but
2228             // the long is < 0. We also must retain a double in the case of
2229             // -0.0, which will compare as == to a long 0 cast to a double
2230             // (bug 4162852).
2231             if (multiplier != 1 && gotDouble) {
2232                 longResult = (long)doubleResult;
2233                 gotDouble = ((doubleResult != (double)longResult) ||
2234                             (doubleResult == 0.0 && 1/doubleResult < 0.0)) &&
2235                             !isParseIntegerOnly();
2236             }
2237 
2238             // cast inside of ?: because of binary numeric promotion, JLS 15.25
2239             return gotDouble ? (Number)doubleResult : (Number)longResult;
2240         }
2241     }
2242 
2243     /**
2244      * Return a BigInteger multiplier.
2245      */
2246     private BigInteger getBigIntegerMultiplier() {
2247         if (bigIntegerMultiplier == null) {
2248             bigIntegerMultiplier = BigInteger.valueOf(multiplier);
2249         }
2250         return bigIntegerMultiplier;
2251     }
2252     private transient BigInteger bigIntegerMultiplier;
2253 
2254     /**
2255      * Return a BigDecimal multiplier.
2256      */
2257     private BigDecimal getBigDecimalMultiplier() {
2258         if (bigDecimalMultiplier == null) {
2259             bigDecimalMultiplier = new BigDecimal(multiplier);
2260         }
2261         return bigDecimalMultiplier;
2262     }
2263     private transient BigDecimal bigDecimalMultiplier;
2264 
2265     private static final int STATUS_INFINITE = 0;
2266     private static final int STATUS_POSITIVE = 1;
2267     private static final int STATUS_LENGTH   = 2;
2268 
2269     /**
2270      * Parse the given text into a number.  The text is parsed beginning at
2271      * parsePosition, until an unparseable character is seen.
2272      * @param text The string to parse.
2273      * @param parsePosition The position at which to being parsing.  Upon
2274      * return, the first unparseable character.
2275      * @param digits The DigitList to set to the parsed value.
2276      * @param isExponent If true, parse an exponent.  This means no
2277      * infinite values and integer only.
2278      * @param status Upon return contains boolean status flags indicating
2279      * whether the value was infinite and whether it was positive.
2280      */
2281     private final boolean subparse(String text, ParsePosition parsePosition,
2282                                    String positivePrefix, String negativePrefix,
2283                                    DigitList digits, boolean isExponent,
2284                                    boolean status[]) {
2285         int position = parsePosition.index;
2286         int oldStart = parsePosition.index;
2287         boolean gotPositive, gotNegative;
2288 
2289         // check for positivePrefix; take longest
2290         gotPositive = text.regionMatches(position, positivePrefix, 0,
2291                 positivePrefix.length());
2292         gotNegative = text.regionMatches(position, negativePrefix, 0,
2293                 negativePrefix.length());
2294 
2295         if (gotPositive && gotNegative) {
2296             if (positivePrefix.length() > negativePrefix.length()) {
2297                 gotNegative = false;
2298             } else if (positivePrefix.length() < negativePrefix.length()) {
2299                 gotPositive = false;
2300             }
2301         }
2302 
2303         if (gotPositive) {
2304             position += positivePrefix.length();
2305         } else if (gotNegative) {
2306             position += negativePrefix.length();
2307         } else {
2308             parsePosition.errorIndex = position;
2309             return false;
2310         }
2311 
2312         position = subparseNumber(text, position, digits, true, isExponent, status);
2313         if (position == -1) {
2314             parsePosition.index = oldStart;
2315             parsePosition.errorIndex = oldStart;
2316             return false;
2317         }
2318 
2319         // Check for suffix
2320         if (!isExponent) {
2321             if (gotPositive) {
2322                 gotPositive = text.regionMatches(position,positiveSuffix,0,
2323                         positiveSuffix.length());
2324             }
2325             if (gotNegative) {
2326                 gotNegative = text.regionMatches(position,negativeSuffix,0,
2327                         negativeSuffix.length());
2328             }
2329 
2330             // If both match, take longest
2331             if (gotPositive && gotNegative) {
2332                 if (positiveSuffix.length() > negativeSuffix.length()) {
2333                     gotNegative = false;
2334                 } else if (positiveSuffix.length() < negativeSuffix.length()) {
2335                     gotPositive = false;
2336                 }
2337             }
2338 
2339             // Fail if neither or both
2340             if (gotPositive == gotNegative) {
2341                 parsePosition.errorIndex = position;
2342                 return false;
2343             }
2344 
2345             parsePosition.index = position +
2346                     (gotPositive ? positiveSuffix.length() : negativeSuffix.length()); // mark success!
2347         } else {
2348             parsePosition.index = position;
2349         }
2350 
2351         status[STATUS_POSITIVE] = gotPositive;
2352         if (parsePosition.index == oldStart) {
2353             parsePosition.errorIndex = position;
2354             return false;
2355         }
2356         return true;
2357     }
2358 
2359     /**
2360      * Parses a number from the given {@code text}. The text is parsed
2361      * beginning at position, until an unparseable character is seen.
2362      *
2363      * @param text the string to parse
2364      * @param position the position at which parsing begins
2365      * @param digits the DigitList to set to the parsed value
2366      * @param checkExponent whether to check for exponential number
2367      * @param isExponent if the exponential part is encountered
2368      * @param status upon return contains boolean status flags indicating
2369      *               whether the value is infinite and whether it is
2370      *               positive
2371      * @return returns the position of the first unparseable character or
2372      *         -1 in case of no valid number parsed
2373      */
2374     int subparseNumber(String text, int position,
2375                        DigitList digits, boolean checkExponent,
2376                        boolean isExponent, boolean status[]) {
2377         // process digits or Inf, find decimal position
2378         status[STATUS_INFINITE] = false;
2379         if (!isExponent && text.regionMatches(position,symbols.getInfinity(),0,
2380                 symbols.getInfinity().length())) {
2381             position += symbols.getInfinity().length();
2382             status[STATUS_INFINITE] = true;
2383         } else {
2384             // We now have a string of digits, possibly with grouping symbols,
2385             // and decimal points.  We want to process these into a DigitList.
2386             // We don't want to put a bunch of leading zeros into the DigitList
2387             // though, so we keep track of the location of the decimal point,
2388             // put only significant digits into the DigitList, and adjust the
2389             // exponent as needed.
2390 
2391             digits.decimalAt = digits.count = 0;
2392             char zero = symbols.getZeroDigit();
2393             char decimal = isCurrencyFormat ?
2394                     symbols.getMonetaryDecimalSeparator() :
2395                     symbols.getDecimalSeparator();
2396             char grouping = symbols.getGroupingSeparator();
2397             String exponentString = symbols.getExponentSeparator();
2398             boolean sawDecimal = false;
2399             boolean sawExponent = false;
2400             boolean sawDigit = false;
2401             int exponent = 0; // Set to the exponent value, if any
2402 
2403             // We have to track digitCount ourselves, because digits.count will
2404             // pin when the maximum allowable digits is reached.
2405             int digitCount = 0;
2406 
2407             int backup = -1;
2408             for (; position < text.length(); ++position) {
2409                 char ch = text.charAt(position);
2410 
2411                 /* We recognize all digit ranges, not only the Latin digit range
2412                  * '0'..'9'.  We do so by using the Character.digit() method,
2413                  * which converts a valid Unicode digit to the range 0..9.
2414                  *
2415                  * The character 'ch' may be a digit.  If so, place its value
2416                  * from 0 to 9 in 'digit'.  First try using the locale digit,
2417                  * which may or MAY NOT be a standard Unicode digit range.  If
2418                  * this fails, try using the standard Unicode digit ranges by
2419                  * calling Character.digit().  If this also fails, digit will
2420                  * have a value outside the range 0..9.
2421                  */
2422                 int digit = ch - zero;
2423                 if (digit < 0 || digit > 9) {
2424                     digit = Character.digit(ch, 10);
2425                 }
2426 
2427                 if (digit == 0) {
2428                     // Cancel out backup setting (see grouping handler below)
2429                     backup = -1; // Do this BEFORE continue statement below!!!
2430                     sawDigit = true;
2431 
2432                     // Handle leading zeros
2433                     if (digits.count == 0) {
2434                         // Ignore leading zeros in integer part of number.
2435                         if (!sawDecimal) {
2436                             continue;
2437                         }
2438 
2439                         // If we have seen the decimal, but no significant
2440                         // digits yet, then we account for leading zeros by
2441                         // decrementing the digits.decimalAt into negative
2442                         // values.
2443                         --digits.decimalAt;
2444                     } else {
2445                         ++digitCount;
2446                         digits.append((char)(digit + '0'));
2447                     }
2448                 } else if (digit > 0 && digit <= 9) { // [sic] digit==0 handled above
2449                     sawDigit = true;
2450                     ++digitCount;
2451                     digits.append((char)(digit + '0'));
2452 
2453                     // Cancel out backup setting (see grouping handler below)
2454                     backup = -1;
2455                 } else if (!isExponent && ch == decimal) {
2456                     // If we're only parsing integers, or if we ALREADY saw the
2457                     // decimal, then don't parse this one.
2458                     if (isParseIntegerOnly() || sawDecimal) {
2459                         break;
2460                     }
2461                     digits.decimalAt = digitCount; // Not digits.count!
2462                     sawDecimal = true;
2463                 } else if (!isExponent && ch == grouping && isGroupingUsed()) {
2464                     if (sawDecimal) {
2465                         break;
2466                     }
2467                     // Ignore grouping characters, if we are using them, but
2468                     // require that they be followed by a digit.  Otherwise
2469                     // we backup and reprocess them.
2470                     backup = position;
2471                 } else if (checkExponent && !isExponent && text.regionMatches(position, exponentString, 0, exponentString.length())
2472                         && !sawExponent) {
2473                     // Process the exponent by recursively calling this method.
2474                     ParsePosition pos = new ParsePosition(position + exponentString.length());
2475                     boolean[] stat = new boolean[STATUS_LENGTH];
2476                     DigitList exponentDigits = new DigitList();
2477 
2478                     if (subparse(text, pos, "", symbols.getMinusSignText(), exponentDigits, true, stat) &&
2479                             exponentDigits.fitsIntoLong(stat[STATUS_POSITIVE], true)) {
2480                         position = pos.index; // Advance past the exponent
2481                         exponent = (int)exponentDigits.getLong();
2482                         if (!stat[STATUS_POSITIVE]) {
2483                             exponent = -exponent;
2484                         }
2485                         sawExponent = true;
2486                     }
2487                     break; // Whether we fail or succeed, we exit this loop
2488                 } else {
2489                     break;
2490                 }
2491             }
2492 
2493             if (backup != -1) {
2494                 position = backup;
2495             }
2496 
2497             // If there was no decimal point we have an integer
2498             if (!sawDecimal) {
2499                 digits.decimalAt = digitCount; // Not digits.count!
2500             }
2501 
2502             // Adjust for exponent, if any
2503             digits.decimalAt += exponent;
2504 
2505             // If none of the text string was recognized.  For example, parse
2506             // "x" with pattern "#0.00" (return index and error index both 0)
2507             // parse "$" with pattern "$#0.00". (return index 0 and error
2508             // index 1).
2509             if (!sawDigit && digitCount == 0) {
2510                 return -1;
2511             }
2512         }
2513         return position;
2514 
2515     }
2516 
2517     /**
2518      * Returns a copy of the decimal format symbols, which is generally not
2519      * changed by the programmer or user.
2520      * @return a copy of the desired DecimalFormatSymbols
2521      * @see java.text.DecimalFormatSymbols
2522      */
2523     public DecimalFormatSymbols getDecimalFormatSymbols() {
2524         try {
2525             // don't allow multiple references
2526             return (DecimalFormatSymbols) symbols.clone();
2527         } catch (Exception foo) {
2528             return null; // should never happen
2529         }
2530     }
2531 
2532 
2533     /**
2534      * Sets the decimal format symbols, which is generally not changed
2535      * by the programmer or user.
2536      * @param newSymbols desired DecimalFormatSymbols
2537      * @see java.text.DecimalFormatSymbols
2538      */
2539     public void setDecimalFormatSymbols(DecimalFormatSymbols newSymbols) {
2540         try {
2541             // don't allow multiple references
2542             symbols = (DecimalFormatSymbols) newSymbols.clone();
2543             expandAffixes();
2544             fastPathCheckNeeded = true;
2545         } catch (Exception foo) {
2546             // should never happen
2547         }
2548     }
2549 
2550     /**
2551      * Get the positive prefix.
2552      * <P>Examples: +123, $123, sFr123
2553      *
2554      * @return the positive prefix
2555      */
2556     public String getPositivePrefix () {
2557         return positivePrefix;
2558     }
2559 
2560     /**
2561      * Set the positive prefix.
2562      * <P>Examples: +123, $123, sFr123
2563      *
2564      * @param newValue the new positive prefix
2565      */
2566     public void setPositivePrefix (String newValue) {
2567         positivePrefix = newValue;
2568         posPrefixPattern = null;
2569         positivePrefixFieldPositions = null;
2570         fastPathCheckNeeded = true;
2571     }
2572 
2573     /**
2574      * Returns the FieldPositions of the fields in the prefix used for
2575      * positive numbers. This is not used if the user has explicitly set
2576      * a positive prefix via {@code setPositivePrefix}. This is
2577      * lazily created.
2578      *
2579      * @return FieldPositions in positive prefix
2580      */
2581     private FieldPosition[] getPositivePrefixFieldPositions() {
2582         if (positivePrefixFieldPositions == null) {
2583             if (posPrefixPattern != null) {
2584                 positivePrefixFieldPositions = expandAffix(posPrefixPattern);
2585             } else {
2586                 positivePrefixFieldPositions = EmptyFieldPositionArray;
2587             }
2588         }
2589         return positivePrefixFieldPositions;
2590     }
2591 
2592     /**
2593      * Get the negative prefix.
2594      * <P>Examples: -123, ($123) (with negative suffix), sFr-123
2595      *
2596      * @return the negative prefix
2597      */
2598     public String getNegativePrefix () {
2599         return negativePrefix;
2600     }
2601 
2602     /**
2603      * Set the negative prefix.
2604      * <P>Examples: -123, ($123) (with negative suffix), sFr-123
2605      *
2606      * @param newValue the new negative prefix
2607      */
2608     public void setNegativePrefix (String newValue) {
2609         negativePrefix = newValue;
2610         negPrefixPattern = null;
2611         fastPathCheckNeeded = true;
2612     }
2613 
2614     /**
2615      * Returns the FieldPositions of the fields in the prefix used for
2616      * negative numbers. This is not used if the user has explicitly set
2617      * a negative prefix via {@code setNegativePrefix}. This is
2618      * lazily created.
2619      *
2620      * @return FieldPositions in positive prefix
2621      */
2622     private FieldPosition[] getNegativePrefixFieldPositions() {
2623         if (negativePrefixFieldPositions == null) {
2624             if (negPrefixPattern != null) {
2625                 negativePrefixFieldPositions = expandAffix(negPrefixPattern);
2626             } else {
2627                 negativePrefixFieldPositions = EmptyFieldPositionArray;
2628             }
2629         }
2630         return negativePrefixFieldPositions;
2631     }
2632 
2633     /**
2634      * Get the positive suffix.
2635      * <P>Example: 123%
2636      *
2637      * @return the positive suffix
2638      */
2639     public String getPositiveSuffix () {
2640         return positiveSuffix;
2641     }
2642 
2643     /**
2644      * Set the positive suffix.
2645      * <P>Example: 123%
2646      *
2647      * @param newValue the new positive suffix
2648      */
2649     public void setPositiveSuffix (String newValue) {
2650         positiveSuffix = newValue;
2651         posSuffixPattern = null;
2652         fastPathCheckNeeded = true;
2653     }
2654 
2655     /**
2656      * Returns the FieldPositions of the fields in the suffix used for
2657      * positive numbers. This is not used if the user has explicitly set
2658      * a positive suffix via {@code setPositiveSuffix}. This is
2659      * lazily created.
2660      *
2661      * @return FieldPositions in positive prefix
2662      */
2663     private FieldPosition[] getPositiveSuffixFieldPositions() {
2664         if (positiveSuffixFieldPositions == null) {
2665             if (posSuffixPattern != null) {
2666                 positiveSuffixFieldPositions = expandAffix(posSuffixPattern);
2667             } else {
2668                 positiveSuffixFieldPositions = EmptyFieldPositionArray;
2669             }
2670         }
2671         return positiveSuffixFieldPositions;
2672     }
2673 
2674     /**
2675      * Get the negative suffix.
2676      * <P>Examples: -123%, ($123) (with positive suffixes)
2677      *
2678      * @return the negative suffix
2679      */
2680     public String getNegativeSuffix () {
2681         return negativeSuffix;
2682     }
2683 
2684     /**
2685      * Set the negative suffix.
2686      * <P>Examples: 123%
2687      *
2688      * @param newValue the new negative suffix
2689      */
2690     public void setNegativeSuffix (String newValue) {
2691         negativeSuffix = newValue;
2692         negSuffixPattern = null;
2693         fastPathCheckNeeded = true;
2694     }
2695 
2696     /**
2697      * Returns the FieldPositions of the fields in the suffix used for
2698      * negative numbers. This is not used if the user has explicitly set
2699      * a negative suffix via {@code setNegativeSuffix}. This is
2700      * lazily created.
2701      *
2702      * @return FieldPositions in positive prefix
2703      */
2704     private FieldPosition[] getNegativeSuffixFieldPositions() {
2705         if (negativeSuffixFieldPositions == null) {
2706             if (negSuffixPattern != null) {
2707                 negativeSuffixFieldPositions = expandAffix(negSuffixPattern);
2708             } else {
2709                 negativeSuffixFieldPositions = EmptyFieldPositionArray;
2710             }
2711         }
2712         return negativeSuffixFieldPositions;
2713     }
2714 
2715     /**
2716      * Gets the multiplier for use in percent, per mille, and similar
2717      * formats.
2718      *
2719      * @return the multiplier
2720      * @see #setMultiplier(int)
2721      */
2722     public int getMultiplier () {
2723         return multiplier;
2724     }
2725 
2726     /**
2727      * Sets the multiplier for use in percent, per mille, and similar
2728      * formats.
2729      * For a percent format, set the multiplier to 100 and the suffixes to
2730      * have '%' (for Arabic, use the Arabic percent sign).
2731      * For a per mille format, set the multiplier to 1000 and the suffixes to
2732      * have '\u2030'.
2733      *
2734      * <P>Example: with multiplier 100, 1.23 is formatted as "123", and
2735      * "123" is parsed into 1.23.
2736      *
2737      * @param newValue the new multiplier
2738      * @see #getMultiplier
2739      */
2740     public void setMultiplier (int newValue) {
2741         multiplier = newValue;
2742         bigDecimalMultiplier = null;
2743         bigIntegerMultiplier = null;
2744         fastPathCheckNeeded = true;
2745     }
2746 
2747     /**
2748      * {@inheritDoc}
2749      */
2750     @Override
2751     public void setGroupingUsed(boolean newValue) {
2752         super.setGroupingUsed(newValue);
2753         fastPathCheckNeeded = true;
2754     }
2755 
2756     /**
2757      * Return the grouping size. Grouping size is the number of digits between
2758      * grouping separators in the integer portion of a number.  For example,
2759      * in the number "123,456.78", the grouping size is 3.
2760      *
2761      * @return the grouping size
2762      * @see #setGroupingSize
2763      * @see java.text.NumberFormat#isGroupingUsed
2764      * @see java.text.DecimalFormatSymbols#getGroupingSeparator
2765      */
2766     public int getGroupingSize () {
2767         return groupingSize;
2768     }
2769 
2770     /**
2771      * Set the grouping size. Grouping size is the number of digits between
2772      * grouping separators in the integer portion of a number.  For example,
2773      * in the number "123,456.78", the grouping size is 3.
2774      * <br>
2775      * The value passed in is converted to a byte, which may lose information.
2776      *
2777      * @param newValue the new grouping size
2778      * @see #getGroupingSize
2779      * @see java.text.NumberFormat#setGroupingUsed
2780      * @see java.text.DecimalFormatSymbols#setGroupingSeparator
2781      */
2782     public void setGroupingSize (int newValue) {
2783         groupingSize = (byte)newValue;
2784         fastPathCheckNeeded = true;
2785     }
2786 
2787     /**
2788      * Allows you to get the behavior of the decimal separator with integers.
2789      * (The decimal separator will always appear with decimals.)
2790      * <P>Example: Decimal ON: 12345 &rarr; 12345.; OFF: 12345 &rarr; 12345
2791      *
2792      * @return {@code true} if the decimal separator is always shown;
2793      *         {@code false} otherwise
2794      */
2795     public boolean isDecimalSeparatorAlwaysShown() {
2796         return decimalSeparatorAlwaysShown;
2797     }
2798 
2799     /**
2800      * Allows you to set the behavior of the decimal separator with integers.
2801      * (The decimal separator will always appear with decimals.)
2802      * <P>Example: Decimal ON: 12345 &rarr; 12345.; OFF: 12345 &rarr; 12345
2803      *
2804      * @param newValue {@code true} if the decimal separator is always shown;
2805      *                 {@code false} otherwise
2806      */
2807     public void setDecimalSeparatorAlwaysShown(boolean newValue) {
2808         decimalSeparatorAlwaysShown = newValue;
2809         fastPathCheckNeeded = true;
2810     }
2811 
2812     /**
2813      * Returns whether the {@link #parse(java.lang.String, java.text.ParsePosition)}
2814      * method returns {@code BigDecimal}. The default value is false.
2815      *
2816      * @return {@code true} if the parse method returns BigDecimal;
2817      *         {@code false} otherwise
2818      * @see #setParseBigDecimal
2819      * @since 1.5
2820      */
2821     public boolean isParseBigDecimal() {
2822         return parseBigDecimal;
2823     }
2824 
2825     /**
2826      * Sets whether the {@link #parse(java.lang.String, java.text.ParsePosition)}
2827      * method returns {@code BigDecimal}.
2828      *
2829      * @param newValue {@code true} if the parse method returns BigDecimal;
2830      *                 {@code false} otherwise
2831      * @see #isParseBigDecimal
2832      * @since 1.5
2833      */
2834     public void setParseBigDecimal(boolean newValue) {
2835         parseBigDecimal = newValue;
2836     }
2837 
2838     /**
2839      * Standard override; no change in semantics.
2840      */
2841     @Override
2842     public Object clone() {
2843         DecimalFormat other = (DecimalFormat) super.clone();
2844         other.symbols = (DecimalFormatSymbols) symbols.clone();
2845         other.digitList = (DigitList) digitList.clone();
2846 
2847         // Fast-path is almost stateless algorithm. The only logical state is the
2848         // isFastPath flag. In addition fastPathCheckNeeded is a sentinel flag
2849         // that forces recalculation of all fast-path fields when set to true.
2850         //
2851         // There is thus no need to clone all the fast-path fields.
2852         // We just only need to set fastPathCheckNeeded to true when cloning,
2853         // and init fastPathData to null as if it were a truly new instance.
2854         // Every fast-path field will be recalculated (only once) at next usage of
2855         // fast-path algorithm.
2856         other.fastPathCheckNeeded = true;
2857         other.isFastPath = false;
2858         other.fastPathData = null;
2859 
2860         return other;
2861     }
2862 
2863     /**
2864      * Overrides equals
2865      */
2866     @Override
2867     public boolean equals(Object obj)
2868     {
2869         if (obj == null)
2870             return false;
2871         if (!super.equals(obj))
2872             return false; // super does class check
2873         DecimalFormat other = (DecimalFormat) obj;
2874         return ((posPrefixPattern == other.posPrefixPattern &&
2875                  positivePrefix.equals(other.positivePrefix))
2876                 || (posPrefixPattern != null &&
2877                     posPrefixPattern.equals(other.posPrefixPattern)))
2878             && ((posSuffixPattern == other.posSuffixPattern &&
2879                  positiveSuffix.equals(other.positiveSuffix))
2880                 || (posSuffixPattern != null &&
2881                     posSuffixPattern.equals(other.posSuffixPattern)))
2882             && ((negPrefixPattern == other.negPrefixPattern &&
2883                  negativePrefix.equals(other.negativePrefix))
2884                 || (negPrefixPattern != null &&
2885                     negPrefixPattern.equals(other.negPrefixPattern)))
2886             && ((negSuffixPattern == other.negSuffixPattern &&
2887                  negativeSuffix.equals(other.negativeSuffix))
2888                 || (negSuffixPattern != null &&
2889                     negSuffixPattern.equals(other.negSuffixPattern)))
2890             && multiplier == other.multiplier
2891             && groupingSize == other.groupingSize
2892             && decimalSeparatorAlwaysShown == other.decimalSeparatorAlwaysShown
2893             && parseBigDecimal == other.parseBigDecimal
2894             && useExponentialNotation == other.useExponentialNotation
2895             && (!useExponentialNotation ||
2896                 minExponentDigits == other.minExponentDigits)
2897             && maximumIntegerDigits == other.maximumIntegerDigits
2898             && minimumIntegerDigits == other.minimumIntegerDigits
2899             && maximumFractionDigits == other.maximumFractionDigits
2900             && minimumFractionDigits == other.minimumFractionDigits
2901             && roundingMode == other.roundingMode
2902             && symbols.equals(other.symbols);
2903     }
2904 
2905     /**
2906      * Overrides hashCode
2907      */
2908     @Override
2909     public int hashCode() {
2910         return super.hashCode() * 37 + positivePrefix.hashCode();
2911         // just enough fields for a reasonable distribution
2912     }
2913 
2914     /**
2915      * Synthesizes a pattern string that represents the current state
2916      * of this Format object.
2917      *
2918      * @return a pattern string
2919      * @see #applyPattern
2920      */
2921     public String toPattern() {
2922         return toPattern( false );
2923     }
2924 
2925     /**
2926      * Synthesizes a localized pattern string that represents the current
2927      * state of this Format object.
2928      *
2929      * @return a localized pattern string
2930      * @see #applyPattern
2931      */
2932     public String toLocalizedPattern() {
2933         return toPattern( true );
2934     }
2935 
2936     /**
2937      * Expand the affix pattern strings into the expanded affix strings.  If any
2938      * affix pattern string is null, do not expand it.  This method should be
2939      * called any time the symbols or the affix patterns change in order to keep
2940      * the expanded affix strings up to date.
2941      */
2942     private void expandAffixes() {
2943         // Reuse one StringBuffer for better performance
2944         StringBuffer buffer = new StringBuffer();
2945         if (posPrefixPattern != null) {
2946             positivePrefix = expandAffix(posPrefixPattern, buffer);
2947             positivePrefixFieldPositions = null;
2948         }
2949         if (posSuffixPattern != null) {
2950             positiveSuffix = expandAffix(posSuffixPattern, buffer);
2951             positiveSuffixFieldPositions = null;
2952         }
2953         if (negPrefixPattern != null) {
2954             negativePrefix = expandAffix(negPrefixPattern, buffer);
2955             negativePrefixFieldPositions = null;
2956         }
2957         if (negSuffixPattern != null) {
2958             negativeSuffix = expandAffix(negSuffixPattern, buffer);
2959             negativeSuffixFieldPositions = null;
2960         }
2961     }
2962 
2963     /**
2964      * Expand an affix pattern into an affix string.  All characters in the
2965      * pattern are literal unless prefixed by QUOTE.  The following characters
2966      * after QUOTE are recognized: PATTERN_PERCENT, PATTERN_PER_MILLE,
2967      * PATTERN_MINUS, and CURRENCY_SIGN.  If CURRENCY_SIGN is doubled (QUOTE +
2968      * CURRENCY_SIGN + CURRENCY_SIGN), it is interpreted as an ISO 4217
2969      * currency code.  Any other character after a QUOTE represents itself.
2970      * QUOTE must be followed by another character; QUOTE may not occur by
2971      * itself at the end of the pattern.
2972      *
2973      * @param pattern the non-null, possibly empty pattern
2974      * @param buffer a scratch StringBuffer; its contents will be lost
2975      * @return the expanded equivalent of pattern
2976      */
2977     private String expandAffix(String pattern, StringBuffer buffer) {
2978         buffer.setLength(0);
2979         for (int i=0; i<pattern.length(); ) {
2980             char c = pattern.charAt(i++);
2981             if (c == QUOTE) {
2982                 c = pattern.charAt(i++);
2983                 switch (c) {
2984                 case CURRENCY_SIGN:
2985                     if (i<pattern.length() &&
2986                         pattern.charAt(i) == CURRENCY_SIGN) {
2987                         ++i;
2988                         buffer.append(symbols.getInternationalCurrencySymbol());
2989                     } else {
2990                         buffer.append(symbols.getCurrencySymbol());
2991                     }
2992                     continue;
2993                 case PATTERN_PERCENT:
2994                     buffer.append(symbols.getPercentText());
2995                     continue;
2996                 case PATTERN_PER_MILLE:
2997                     buffer.append(symbols.getPerMillText());
2998                     continue;
2999                 case PATTERN_MINUS:
3000                     buffer.append(symbols.getMinusSignText());
3001                     continue;
3002                 }
3003             }
3004             buffer.append(c);
3005         }
3006         return buffer.toString();
3007     }
3008 
3009     /**
3010      * Expand an affix pattern into an array of FieldPositions describing
3011      * how the pattern would be expanded.
3012      * All characters in the
3013      * pattern are literal unless prefixed by QUOTE.  The following characters
3014      * after QUOTE are recognized: PATTERN_PERCENT, PATTERN_PER_MILLE,
3015      * PATTERN_MINUS, and CURRENCY_SIGN.  If CURRENCY_SIGN is doubled (QUOTE +
3016      * CURRENCY_SIGN + CURRENCY_SIGN), it is interpreted as an ISO 4217
3017      * currency code.  Any other character after a QUOTE represents itself.
3018      * QUOTE must be followed by another character; QUOTE may not occur by
3019      * itself at the end of the pattern.
3020      *
3021      * @param pattern the non-null, possibly empty pattern
3022      * @return FieldPosition array of the resulting fields.
3023      */
3024     private FieldPosition[] expandAffix(String pattern) {
3025         ArrayList<FieldPosition> positions = null;
3026         int stringIndex = 0;
3027         for (int i=0; i<pattern.length(); ) {
3028             char c = pattern.charAt(i++);
3029             if (c == QUOTE) {
3030                 Format.Field fieldID = null;
3031                 String string = null;
3032                 c = pattern.charAt(i++);
3033                 switch (c) {
3034                 case CURRENCY_SIGN:
3035                     if (i<pattern.length() &&
3036                         pattern.charAt(i) == CURRENCY_SIGN) {
3037                         ++i;
3038                         string = symbols.getInternationalCurrencySymbol();
3039                     } else {
3040                         string = symbols.getCurrencySymbol();
3041                     }
3042                     fieldID = Field.CURRENCY;
3043                     break;
3044                 case PATTERN_PERCENT:
3045                     string = symbols.getPercentText();
3046                     fieldID = Field.PERCENT;
3047                     break;
3048                 case PATTERN_PER_MILLE:
3049                     string = symbols.getPerMillText();
3050                     fieldID = Field.PERMILLE;
3051                     break;
3052                 case PATTERN_MINUS:
3053                     string = symbols.getMinusSignText();
3054                     fieldID = Field.SIGN;
3055                     break;
3056                 }
3057 
3058                 if (fieldID != null && !string.isEmpty()) {
3059                     if (positions == null) {
3060                         positions = new ArrayList<>(2);
3061                     }
3062                     FieldPosition fp = new FieldPosition(fieldID);
3063                     fp.setBeginIndex(stringIndex);
3064                     fp.setEndIndex(stringIndex + string.length());
3065                     positions.add(fp);
3066                     stringIndex += string.length();
3067                     continue;
3068                 }
3069             }
3070             stringIndex++;
3071         }
3072         if (positions != null) {
3073             return positions.toArray(EmptyFieldPositionArray);
3074         }
3075         return EmptyFieldPositionArray;
3076     }
3077 
3078     /**
3079      * Appends an affix pattern to the given StringBuffer, quoting special
3080      * characters as needed.  Uses the internal affix pattern, if that exists,
3081      * or the literal affix, if the internal affix pattern is null.  The
3082      * appended string will generate the same affix pattern (or literal affix)
3083      * when passed to toPattern().
3084      *
3085      * @param buffer the affix string is appended to this
3086      * @param affixPattern a pattern such as posPrefixPattern; may be null
3087      * @param expAffix a corresponding expanded affix, such as positivePrefix.
3088      * Ignored unless affixPattern is null.  If affixPattern is null, then
3089      * expAffix is appended as a literal affix.
3090      * @param localized true if the appended pattern should contain localized
3091      * pattern characters; otherwise, non-localized pattern chars are appended
3092      */
3093     private void appendAffix(StringBuffer buffer, String affixPattern,
3094                              String expAffix, boolean localized) {
3095         if (affixPattern == null) {
3096             appendAffix(buffer, expAffix, localized);
3097         } else {
3098             int i;
3099             for (int pos=0; pos<affixPattern.length(); pos=i) {
3100                 i = affixPattern.indexOf(QUOTE, pos);
3101                 if (i < 0) {
3102                     appendAffix(buffer, affixPattern.substring(pos), localized);
3103                     break;
3104                 }
3105                 if (i > pos) {
3106                     appendAffix(buffer, affixPattern.substring(pos, i), localized);
3107                 }
3108                 char c = affixPattern.charAt(++i);
3109                 ++i;
3110                 if (c == QUOTE) {
3111                     buffer.append(c);
3112                     // Fall through and append another QUOTE below
3113                 } else if (c == CURRENCY_SIGN &&
3114                            i<affixPattern.length() &&
3115                            affixPattern.charAt(i) == CURRENCY_SIGN) {
3116                     ++i;
3117                     buffer.append(c);
3118                     // Fall through and append another CURRENCY_SIGN below
3119                 } else if (localized) {
3120                     switch (c) {
3121                     case PATTERN_PERCENT:
3122                         buffer.append(symbols.getPercentText());
3123                         continue;
3124                     case PATTERN_PER_MILLE:
3125                         buffer.append(symbols.getPerMillText());
3126                         continue;
3127                     case PATTERN_MINUS:
3128                         buffer.append(symbols.getMinusSignText());
3129                         continue;
3130                     }
3131                 }
3132                 buffer.append(c);
3133             }
3134         }
3135     }
3136 
3137     /**
3138      * Append an affix to the given StringBuffer, using quotes if
3139      * there are special characters.  Single quotes themselves must be
3140      * escaped in either case.
3141      */
3142     private void appendAffix(StringBuffer buffer, String affix, boolean localized) {
3143         boolean needQuote;
3144         if (localized) {
3145             needQuote = affix.indexOf(symbols.getZeroDigit()) >= 0
3146                 || affix.indexOf(symbols.getGroupingSeparator()) >= 0
3147                 || affix.indexOf(symbols.getDecimalSeparator()) >= 0
3148                 || affix.indexOf(symbols.getPercentText()) >= 0
3149                 || affix.indexOf(symbols.getPerMillText()) >= 0
3150                 || affix.indexOf(symbols.getDigit()) >= 0
3151                 || affix.indexOf(symbols.getPatternSeparator()) >= 0
3152                 || affix.indexOf(symbols.getMinusSignText()) >= 0
3153                 || affix.indexOf(CURRENCY_SIGN) >= 0;
3154         } else {
3155             needQuote = affix.indexOf(PATTERN_ZERO_DIGIT) >= 0
3156                 || affix.indexOf(PATTERN_GROUPING_SEPARATOR) >= 0
3157                 || affix.indexOf(PATTERN_DECIMAL_SEPARATOR) >= 0
3158                 || affix.indexOf(PATTERN_PERCENT) >= 0
3159                 || affix.indexOf(PATTERN_PER_MILLE) >= 0
3160                 || affix.indexOf(PATTERN_DIGIT) >= 0
3161                 || affix.indexOf(PATTERN_SEPARATOR) >= 0
3162                 || affix.indexOf(PATTERN_MINUS) >= 0
3163                 || affix.indexOf(CURRENCY_SIGN) >= 0;
3164         }
3165         if (needQuote) buffer.append('\'');
3166         if (affix.indexOf('\'') < 0) buffer.append(affix);
3167         else {
3168             for (int j=0; j<affix.length(); ++j) {
3169                 char c = affix.charAt(j);
3170                 buffer.append(c);
3171                 if (c == '\'') buffer.append(c);
3172             }
3173         }
3174         if (needQuote) buffer.append('\'');
3175     }
3176 
3177     /**
3178      * Does the real work of generating a pattern.  */
3179     private String toPattern(boolean localized) {
3180         StringBuffer result = new StringBuffer();
3181         for (int j = 1; j >= 0; --j) {
3182             if (j == 1)
3183                 appendAffix(result, posPrefixPattern, positivePrefix, localized);
3184             else appendAffix(result, negPrefixPattern, negativePrefix, localized);
3185             int i;
3186             int digitCount = useExponentialNotation
3187                         ? getMaximumIntegerDigits()
3188                         : Math.max(groupingSize, getMinimumIntegerDigits())+1;
3189             for (i = digitCount; i > 0; --i) {
3190                 if (i != digitCount && isGroupingUsed() && groupingSize != 0 &&
3191                     i % groupingSize == 0) {
3192                     result.append(localized ? symbols.getGroupingSeparator() :
3193                                   PATTERN_GROUPING_SEPARATOR);
3194                 }
3195                 result.append(i <= getMinimumIntegerDigits()
3196                     ? (localized ? symbols.getZeroDigit() : PATTERN_ZERO_DIGIT)
3197                     : (localized ? symbols.getDigit() : PATTERN_DIGIT));
3198             }
3199             if (getMaximumFractionDigits() > 0 || decimalSeparatorAlwaysShown)
3200                 result.append(localized ? symbols.getDecimalSeparator() :
3201                               PATTERN_DECIMAL_SEPARATOR);
3202             for (i = 0; i < getMaximumFractionDigits(); ++i) {
3203                 if (i < getMinimumFractionDigits()) {
3204                     result.append(localized ? symbols.getZeroDigit() :
3205                                   PATTERN_ZERO_DIGIT);
3206                 } else {
3207                     result.append(localized ? symbols.getDigit() :
3208                                   PATTERN_DIGIT);
3209                 }
3210             }
3211         if (useExponentialNotation)
3212         {
3213             result.append(localized ? symbols.getExponentSeparator() :
3214                   PATTERN_EXPONENT);
3215         for (i=0; i<minExponentDigits; ++i)
3216                     result.append(localized ? symbols.getZeroDigit() :
3217                                   PATTERN_ZERO_DIGIT);
3218         }
3219             if (j == 1) {
3220                 appendAffix(result, posSuffixPattern, positiveSuffix, localized);
3221                 if ((negSuffixPattern == posSuffixPattern && // n == p == null
3222                      negativeSuffix.equals(positiveSuffix))
3223                     || (negSuffixPattern != null &&
3224                         negSuffixPattern.equals(posSuffixPattern))) {
3225                     if ((negPrefixPattern != null && posPrefixPattern != null &&
3226                          negPrefixPattern.equals("'-" + posPrefixPattern)) ||
3227                         (negPrefixPattern == posPrefixPattern && // n == p == null
3228                          negativePrefix.equals(symbols.getMinusSignText() + positivePrefix)))
3229                         break;
3230                 }
3231                 result.append(localized ? symbols.getPatternSeparator() :
3232                               PATTERN_SEPARATOR);
3233             } else appendAffix(result, negSuffixPattern, negativeSuffix, localized);
3234         }
3235         return result.toString();
3236     }
3237 
3238     /**
3239      * Apply the given pattern to this Format object.  A pattern is a
3240      * short-hand specification for the various formatting properties.
3241      * These properties can also be changed individually through the
3242      * various setter methods.
3243      * <p>
3244      * There is no limit to integer digits set
3245      * by this routine, since that is the typical end-user desire;
3246      * use setMaximumInteger if you want to set a real value.
3247      * For negative numbers, use a second pattern, separated by a semicolon
3248      * <P>Example {@code "#,#00.0#"} &rarr; 1,234.56
3249      * <P>This means a minimum of 2 integer digits, 1 fraction digit, and
3250      * a maximum of 2 fraction digits.
3251      * <p>Example: {@code "#,#00.0#;(#,#00.0#)"} for negatives in
3252      * parentheses.
3253      * <p>In negative patterns, the minimum and maximum counts are ignored;
3254      * these are presumed to be set in the positive pattern.
3255      *
3256      * @param pattern a new pattern
3257      * @exception NullPointerException if {@code pattern} is null
3258      * @exception IllegalArgumentException if the given pattern is invalid.
3259      */
3260     public void applyPattern(String pattern) {
3261         applyPattern(pattern, false);
3262     }
3263 
3264     /**
3265      * Apply the given pattern to this Format object.  The pattern
3266      * is assumed to be in a localized notation. A pattern is a
3267      * short-hand specification for the various formatting properties.
3268      * These properties can also be changed individually through the
3269      * various setter methods.
3270      * <p>
3271      * There is no limit to integer digits set
3272      * by this routine, since that is the typical end-user desire;
3273      * use setMaximumInteger if you want to set a real value.
3274      * For negative numbers, use a second pattern, separated by a semicolon
3275      * <P>Example {@code "#,#00.0#"} &rarr; 1,234.56
3276      * <P>This means a minimum of 2 integer digits, 1 fraction digit, and
3277      * a maximum of 2 fraction digits.
3278      * <p>Example: {@code "#,#00.0#;(#,#00.0#)"} for negatives in
3279      * parentheses.
3280      * <p>In negative patterns, the minimum and maximum counts are ignored;
3281      * these are presumed to be set in the positive pattern.
3282      *
3283      * @param pattern a new pattern
3284      * @exception NullPointerException if {@code pattern} is null
3285      * @exception IllegalArgumentException if the given pattern is invalid.
3286      */
3287     public void applyLocalizedPattern(String pattern) {
3288         applyPattern(pattern, true);
3289     }
3290 
3291     /**
3292      * Does the real work of applying a pattern.
3293      */
3294     private void applyPattern(String pattern, boolean localized) {
3295         char zeroDigit         = PATTERN_ZERO_DIGIT;
3296         char groupingSeparator = PATTERN_GROUPING_SEPARATOR;
3297         char decimalSeparator  = PATTERN_DECIMAL_SEPARATOR;
3298         char percent           = PATTERN_PERCENT;
3299         char perMill           = PATTERN_PER_MILLE;
3300         char digit             = PATTERN_DIGIT;
3301         char separator         = PATTERN_SEPARATOR;
3302         String exponent        = PATTERN_EXPONENT;
3303         char minus             = PATTERN_MINUS;
3304         if (localized) {
3305             zeroDigit         = symbols.getZeroDigit();
3306             groupingSeparator = symbols.getGroupingSeparator();
3307             decimalSeparator  = symbols.getDecimalSeparator();
3308             percent           = symbols.getPercent();
3309             perMill           = symbols.getPerMill();
3310             digit             = symbols.getDigit();
3311             separator         = symbols.getPatternSeparator();
3312             exponent          = symbols.getExponentSeparator();
3313             minus             = symbols.getMinusSign();
3314         }
3315         boolean gotNegative = false;
3316         decimalSeparatorAlwaysShown = false;
3317         isCurrencyFormat = false;
3318         useExponentialNotation = false;
3319 
3320         int start = 0;
3321         for (int j = 1; j >= 0 && start < pattern.length(); --j) {
3322             boolean inQuote = false;
3323             StringBuffer prefix = new StringBuffer();
3324             StringBuffer suffix = new StringBuffer();
3325             int decimalPos = -1;
3326             int multiplier = 1;
3327             int digitLeftCount = 0, zeroDigitCount = 0, digitRightCount = 0;
3328             byte groupingCount = -1;
3329 
3330             // The phase ranges from 0 to 2.  Phase 0 is the prefix.  Phase 1 is
3331             // the section of the pattern with digits, decimal separator,
3332             // grouping characters.  Phase 2 is the suffix.  In phases 0 and 2,
3333             // percent, per mille, and currency symbols are recognized and
3334             // translated.  The separation of the characters into phases is
3335             // strictly enforced; if phase 1 characters are to appear in the
3336             // suffix, for example, they must be quoted.
3337             int phase = 0;
3338 
3339             // The affix is either the prefix or the suffix.
3340             StringBuffer affix = prefix;
3341 
3342             for (int pos = start; pos < pattern.length(); ++pos) {
3343                 char ch = pattern.charAt(pos);
3344                 switch (phase) {
3345                 case 0:
3346                 case 2:
3347                     // Process the prefix / suffix characters
3348                     if (inQuote) {
3349                         // A quote within quotes indicates either the closing
3350                         // quote or two quotes, which is a quote literal. That
3351                         // is, we have the second quote in 'do' or 'don''t'.
3352                         if (ch == QUOTE) {
3353                             if ((pos+1) < pattern.length() &&
3354                                 pattern.charAt(pos+1) == QUOTE) {
3355                                 ++pos;
3356                                 affix.append("''"); // 'don''t'
3357                             } else {
3358                                 inQuote = false; // 'do'
3359                             }
3360                             continue;
3361                         }
3362                     } else {
3363                         // Process unquoted characters seen in prefix or suffix
3364                         // phase.
3365                         if (ch == digit ||
3366                             ch == zeroDigit ||
3367                             ch == groupingSeparator ||
3368                             ch == decimalSeparator) {
3369                             phase = 1;
3370                             --pos; // Reprocess this character
3371                             continue;
3372                         } else if (ch == CURRENCY_SIGN) {
3373                             // Use lookahead to determine if the currency sign
3374                             // is doubled or not.
3375                             boolean doubled = (pos + 1) < pattern.length() &&
3376                                 pattern.charAt(pos + 1) == CURRENCY_SIGN;
3377                             if (doubled) { // Skip over the doubled character
3378                              ++pos;
3379                             }
3380                             isCurrencyFormat = true;
3381                             affix.append(doubled ? "'\u00A4\u00A4" : "'\u00A4");
3382                             continue;
3383                         } else if (ch == QUOTE) {
3384                             // A quote outside quotes indicates either the
3385                             // opening quote or two quotes, which is a quote
3386                             // literal. That is, we have the first quote in 'do'
3387                             // or o''clock.
3388                             if (ch == QUOTE) {
3389                                 if ((pos+1) < pattern.length() &&
3390                                     pattern.charAt(pos+1) == QUOTE) {
3391                                     ++pos;
3392                                     affix.append("''"); // o''clock
3393                                 } else {
3394                                     inQuote = true; // 'do'
3395                                 }
3396                                 continue;
3397                             }
3398                         } else if (ch == separator) {
3399                             // Don't allow separators before we see digit
3400                             // characters of phase 1, and don't allow separators
3401                             // in the second pattern (j == 0).
3402                             if (phase == 0 || j == 0) {
3403                                 throw new IllegalArgumentException("Unquoted special character '" +
3404                                     ch + "' in pattern \"" + pattern + '"');
3405                             }
3406                             start = pos + 1;
3407                             pos = pattern.length();
3408                             continue;
3409                         }
3410 
3411                         // Next handle characters which are appended directly.
3412                         else if (ch == percent) {
3413                             if (multiplier != 1) {
3414                                 throw new IllegalArgumentException("Too many percent/per mille characters in pattern \"" +
3415                                     pattern + '"');
3416                             }
3417                             multiplier = 100;
3418                             affix.append("'%");
3419                             continue;
3420                         } else if (ch == perMill) {
3421                             if (multiplier != 1) {
3422                                 throw new IllegalArgumentException("Too many percent/per mille characters in pattern \"" +
3423                                     pattern + '"');
3424                             }
3425                             multiplier = 1000;
3426                             affix.append("'\u2030");
3427                             continue;
3428                         } else if (ch == minus) {
3429                             affix.append("'-");
3430                             continue;
3431                         }
3432                     }
3433                     // Note that if we are within quotes, or if this is an
3434                     // unquoted, non-special character, then we usually fall
3435                     // through to here.
3436                     affix.append(ch);
3437                     break;
3438 
3439                 case 1:
3440                     // The negative subpattern (j = 0) serves only to specify the
3441                     // negative prefix and suffix, so all the phase 1 characters
3442                     // e.g. digits, zeroDigit, groupingSeparator,
3443                     // decimalSeparator, exponent are ignored
3444                     if (j == 0) {
3445                         while (pos < pattern.length()) {
3446                             char negPatternChar = pattern.charAt(pos);
3447                             if (negPatternChar == digit
3448                                     || negPatternChar == zeroDigit
3449                                     || negPatternChar == groupingSeparator
3450                                     || negPatternChar == decimalSeparator) {
3451                                 ++pos;
3452                             } else if (pattern.regionMatches(pos, exponent,
3453                                     0, exponent.length())) {
3454                                 pos = pos + exponent.length();
3455                             } else {
3456                                 // Not a phase 1 character, consider it as
3457                                 // suffix and parse it in phase 2
3458                                 --pos; //process it again in outer loop
3459                                 phase = 2;
3460                                 affix = suffix;
3461                                 break;
3462                             }
3463                         }
3464                         continue;
3465                     }
3466 
3467                     // Process the digits, decimal, and grouping characters. We
3468                     // record five pieces of information. We expect the digits
3469                     // to occur in the pattern ####0000.####, and we record the
3470                     // number of left digits, zero (central) digits, and right
3471                     // digits. The position of the last grouping character is
3472                     // recorded (should be somewhere within the first two blocks
3473                     // of characters), as is the position of the decimal point,
3474                     // if any (should be in the zero digits). If there is no
3475                     // decimal point, then there should be no right digits.
3476                     if (ch == digit) {
3477                         if (zeroDigitCount > 0) {
3478                             ++digitRightCount;
3479                         } else {
3480                             ++digitLeftCount;
3481                         }
3482                         if (groupingCount >= 0 && decimalPos < 0) {
3483                             ++groupingCount;
3484                         }
3485                     } else if (ch == zeroDigit) {
3486                         if (digitRightCount > 0) {
3487                             throw new IllegalArgumentException("Unexpected '0' in pattern \"" +
3488                                 pattern + '"');
3489                         }
3490                         ++zeroDigitCount;
3491                         if (groupingCount >= 0 && decimalPos < 0) {
3492                             ++groupingCount;
3493                         }
3494                     } else if (ch == groupingSeparator) {
3495                         groupingCount = 0;
3496                     } else if (ch == decimalSeparator) {
3497                         if (decimalPos >= 0) {
3498                             throw new IllegalArgumentException("Multiple decimal separators in pattern \"" +
3499                                 pattern + '"');
3500                         }
3501                         decimalPos = digitLeftCount + zeroDigitCount + digitRightCount;
3502                     } else if (pattern.regionMatches(pos, exponent, 0, exponent.length())){
3503                         if (useExponentialNotation) {
3504                             throw new IllegalArgumentException("Multiple exponential " +
3505                                 "symbols in pattern \"" + pattern + '"');
3506                         }
3507                         useExponentialNotation = true;
3508                         minExponentDigits = 0;
3509 
3510                         // Use lookahead to parse out the exponential part
3511                         // of the pattern, then jump into phase 2.
3512                         pos = pos+exponent.length();
3513                          while (pos < pattern.length() &&
3514                                pattern.charAt(pos) == zeroDigit) {
3515                             ++minExponentDigits;
3516                             ++pos;
3517                         }
3518 
3519                         if ((digitLeftCount + zeroDigitCount) < 1 ||
3520                             minExponentDigits < 1) {
3521                             throw new IllegalArgumentException("Malformed exponential " +
3522                                 "pattern \"" + pattern + '"');
3523                         }
3524 
3525                         // Transition to phase 2
3526                         phase = 2;
3527                         affix = suffix;
3528                         --pos;
3529                         continue;
3530                     } else {
3531                         phase = 2;
3532                         affix = suffix;
3533                         --pos;
3534                         continue;
3535                     }
3536                     break;
3537                 }
3538             }
3539 
3540             // Handle patterns with no '0' pattern character. These patterns
3541             // are legal, but must be interpreted.  "##.###" -> "#0.###".
3542             // ".###" -> ".0##".
3543             /* We allow patterns of the form "####" to produce a zeroDigitCount
3544              * of zero (got that?); although this seems like it might make it
3545              * possible for format() to produce empty strings, format() checks
3546              * for this condition and outputs a zero digit in this situation.
3547              * Having a zeroDigitCount of zero yields a minimum integer digits
3548              * of zero, which allows proper round-trip patterns.  That is, we
3549              * don't want "#" to become "#0" when toPattern() is called (even
3550              * though that's what it really is, semantically).
3551              */
3552             if (zeroDigitCount == 0 && digitLeftCount > 0 && decimalPos >= 0) {
3553                 // Handle "###.###" and "###." and ".###"
3554                 int n = decimalPos;
3555                 if (n == 0) { // Handle ".###"
3556                     ++n;
3557                 }
3558                 digitRightCount = digitLeftCount - n;
3559                 digitLeftCount = n - 1;
3560                 zeroDigitCount = 1;
3561             }
3562 
3563             // Do syntax checking on the digits.
3564             if ((decimalPos < 0 && digitRightCount > 0) ||
3565                 (decimalPos >= 0 && (decimalPos < digitLeftCount ||
3566                  decimalPos > (digitLeftCount + zeroDigitCount))) ||
3567                  groupingCount == 0 || inQuote) {
3568                 throw new IllegalArgumentException("Malformed pattern \"" +
3569                     pattern + '"');
3570             }
3571 
3572             if (j == 1) {
3573                 posPrefixPattern = prefix.toString();
3574                 posSuffixPattern = suffix.toString();
3575                 negPrefixPattern = posPrefixPattern;   // assume these for now
3576                 negSuffixPattern = posSuffixPattern;
3577                 int digitTotalCount = digitLeftCount + zeroDigitCount + digitRightCount;
3578                 /* The effectiveDecimalPos is the position the decimal is at or
3579                  * would be at if there is no decimal. Note that if decimalPos<0,
3580                  * then digitTotalCount == digitLeftCount + zeroDigitCount.
3581                  */
3582                 int effectiveDecimalPos = decimalPos >= 0 ?
3583                     decimalPos : digitTotalCount;
3584                 setMinimumIntegerDigits(effectiveDecimalPos - digitLeftCount);
3585                 setMaximumIntegerDigits(useExponentialNotation ?
3586                     digitLeftCount + getMinimumIntegerDigits() :
3587                     MAXIMUM_INTEGER_DIGITS);
3588                 setMaximumFractionDigits(decimalPos >= 0 ?
3589                     (digitTotalCount - decimalPos) : 0);
3590                 setMinimumFractionDigits(decimalPos >= 0 ?
3591                     (digitLeftCount + zeroDigitCount - decimalPos) : 0);
3592                 setGroupingUsed(groupingCount > 0);
3593                 this.groupingSize = (groupingCount > 0) ? groupingCount : 0;
3594                 this.multiplier = multiplier;
3595                 setDecimalSeparatorAlwaysShown(decimalPos == 0 ||
3596                     decimalPos == digitTotalCount);
3597             } else {
3598                 negPrefixPattern = prefix.toString();
3599                 negSuffixPattern = suffix.toString();
3600                 gotNegative = true;
3601             }
3602         }
3603 
3604         if (pattern.isEmpty()) {
3605             posPrefixPattern = posSuffixPattern = "";
3606             setMinimumIntegerDigits(0);
3607             setMaximumIntegerDigits(MAXIMUM_INTEGER_DIGITS);
3608             setMinimumFractionDigits(0);
3609             setMaximumFractionDigits(MAXIMUM_FRACTION_DIGITS);
3610         }
3611 
3612         // If there was no negative pattern, or if the negative pattern is
3613         // identical to the positive pattern, then prepend the minus sign to
3614         // the positive pattern to form the negative pattern.
3615         if (!gotNegative ||
3616             (negPrefixPattern.equals(posPrefixPattern)
3617              && negSuffixPattern.equals(posSuffixPattern))) {
3618             negSuffixPattern = posSuffixPattern;
3619             negPrefixPattern = "'-" + posPrefixPattern;
3620         }
3621 
3622         expandAffixes();
3623     }
3624 
3625     /**
3626      * Sets the maximum number of digits allowed in the integer portion of a
3627      * number.
3628      * For formatting numbers other than {@code BigInteger} and
3629      * {@code BigDecimal} objects, the lower of {@code newValue} and
3630      * 309 is used. Negative input values are replaced with 0.
3631      * @see NumberFormat#setMaximumIntegerDigits
3632      */
3633     @Override
3634     public void setMaximumIntegerDigits(int newValue) {
3635         maximumIntegerDigits = Math.min(Math.max(0, newValue), MAXIMUM_INTEGER_DIGITS);
3636         super.setMaximumIntegerDigits((maximumIntegerDigits > DOUBLE_INTEGER_DIGITS) ?
3637             DOUBLE_INTEGER_DIGITS : maximumIntegerDigits);
3638         if (minimumIntegerDigits > maximumIntegerDigits) {
3639             minimumIntegerDigits = maximumIntegerDigits;
3640             super.setMinimumIntegerDigits((minimumIntegerDigits > DOUBLE_INTEGER_DIGITS) ?
3641                 DOUBLE_INTEGER_DIGITS : minimumIntegerDigits);
3642         }
3643         fastPathCheckNeeded = true;
3644     }
3645 
3646     /**
3647      * Sets the minimum number of digits allowed in the integer portion of a
3648      * number.
3649      * For formatting numbers other than {@code BigInteger} and
3650      * {@code BigDecimal} objects, the lower of {@code newValue} and
3651      * 309 is used. Negative input values are replaced with 0.
3652      * @see NumberFormat#setMinimumIntegerDigits
3653      */
3654     @Override
3655     public void setMinimumIntegerDigits(int newValue) {
3656         minimumIntegerDigits = Math.min(Math.max(0, newValue), MAXIMUM_INTEGER_DIGITS);
3657         super.setMinimumIntegerDigits((minimumIntegerDigits > DOUBLE_INTEGER_DIGITS) ?
3658             DOUBLE_INTEGER_DIGITS : minimumIntegerDigits);
3659         if (minimumIntegerDigits > maximumIntegerDigits) {
3660             maximumIntegerDigits = minimumIntegerDigits;
3661             super.setMaximumIntegerDigits((maximumIntegerDigits > DOUBLE_INTEGER_DIGITS) ?
3662                 DOUBLE_INTEGER_DIGITS : maximumIntegerDigits);
3663         }
3664         fastPathCheckNeeded = true;
3665     }
3666 
3667     /**
3668      * Sets the maximum number of digits allowed in the fraction portion of a
3669      * number.
3670      * For formatting numbers other than {@code BigInteger} and
3671      * {@code BigDecimal} objects, the lower of {@code newValue} and
3672      * 340 is used. Negative input values are replaced with 0.
3673      * @see NumberFormat#setMaximumFractionDigits
3674      */
3675     @Override
3676     public void setMaximumFractionDigits(int newValue) {
3677         maximumFractionDigits = Math.min(Math.max(0, newValue), MAXIMUM_FRACTION_DIGITS);
3678         super.setMaximumFractionDigits((maximumFractionDigits > DOUBLE_FRACTION_DIGITS) ?
3679             DOUBLE_FRACTION_DIGITS : maximumFractionDigits);
3680         if (minimumFractionDigits > maximumFractionDigits) {
3681             minimumFractionDigits = maximumFractionDigits;
3682             super.setMinimumFractionDigits((minimumFractionDigits > DOUBLE_FRACTION_DIGITS) ?
3683                 DOUBLE_FRACTION_DIGITS : minimumFractionDigits);
3684         }
3685         fastPathCheckNeeded = true;
3686     }
3687 
3688     /**
3689      * Sets the minimum number of digits allowed in the fraction portion of a
3690      * number.
3691      * For formatting numbers other than {@code BigInteger} and
3692      * {@code BigDecimal} objects, the lower of {@code newValue} and
3693      * 340 is used. Negative input values are replaced with 0.
3694      * @see NumberFormat#setMinimumFractionDigits
3695      */
3696     @Override
3697     public void setMinimumFractionDigits(int newValue) {
3698         minimumFractionDigits = Math.min(Math.max(0, newValue), MAXIMUM_FRACTION_DIGITS);
3699         super.setMinimumFractionDigits((minimumFractionDigits > DOUBLE_FRACTION_DIGITS) ?
3700             DOUBLE_FRACTION_DIGITS : minimumFractionDigits);
3701         if (minimumFractionDigits > maximumFractionDigits) {
3702             maximumFractionDigits = minimumFractionDigits;
3703             super.setMaximumFractionDigits((maximumFractionDigits > DOUBLE_FRACTION_DIGITS) ?
3704                 DOUBLE_FRACTION_DIGITS : maximumFractionDigits);
3705         }
3706         fastPathCheckNeeded = true;
3707     }
3708 
3709     /**
3710      * Gets the maximum number of digits allowed in the integer portion of a
3711      * number.
3712      * For formatting numbers other than {@code BigInteger} and
3713      * {@code BigDecimal} objects, the lower of the return value and
3714      * 309 is used.
3715      * @see #setMaximumIntegerDigits
3716      */
3717     @Override
3718     public int getMaximumIntegerDigits() {
3719         return maximumIntegerDigits;
3720     }
3721 
3722     /**
3723      * Gets the minimum number of digits allowed in the integer portion of a
3724      * number.
3725      * For formatting numbers other than {@code BigInteger} and
3726      * {@code BigDecimal} objects, the lower of the return value and
3727      * 309 is used.
3728      * @see #setMinimumIntegerDigits
3729      */
3730     @Override
3731     public int getMinimumIntegerDigits() {
3732         return minimumIntegerDigits;
3733     }
3734 
3735     /**
3736      * Gets the maximum number of digits allowed in the fraction portion of a
3737      * number.
3738      * For formatting numbers other than {@code BigInteger} and
3739      * {@code BigDecimal} objects, the lower of the return value and
3740      * 340 is used.
3741      * @see #setMaximumFractionDigits
3742      */
3743     @Override
3744     public int getMaximumFractionDigits() {
3745         return maximumFractionDigits;
3746     }
3747 
3748     /**
3749      * Gets the minimum number of digits allowed in the fraction portion of a
3750      * number.
3751      * For formatting numbers other than {@code BigInteger} and
3752      * {@code BigDecimal} objects, the lower of the return value and
3753      * 340 is used.
3754      * @see #setMinimumFractionDigits
3755      */
3756     @Override
3757     public int getMinimumFractionDigits() {
3758         return minimumFractionDigits;
3759     }
3760 
3761     /**
3762      * Gets the currency used by this decimal format when formatting
3763      * currency values.
3764      * The currency is obtained by calling
3765      * {@link DecimalFormatSymbols#getCurrency DecimalFormatSymbols.getCurrency}
3766      * on this number format's symbols.
3767      *
3768      * @return the currency used by this decimal format, or {@code null}
3769      * @since 1.4
3770      */
3771     @Override
3772     public Currency getCurrency() {
3773         return symbols.getCurrency();
3774     }
3775 
3776     /**
3777      * Sets the currency used by this number format when formatting
3778      * currency values. This does not update the minimum or maximum
3779      * number of fraction digits used by the number format.
3780      * The currency is set by calling
3781      * {@link DecimalFormatSymbols#setCurrency DecimalFormatSymbols.setCurrency}
3782      * on this number format's symbols.
3783      *
3784      * @param currency the new currency to be used by this decimal format
3785      * @exception NullPointerException if {@code currency} is null
3786      * @since 1.4
3787      */
3788     @Override
3789     public void setCurrency(Currency currency) {
3790         if (currency != symbols.getCurrency()) {
3791             symbols.setCurrency(currency);
3792             if (isCurrencyFormat) {
3793                 expandAffixes();
3794             }
3795         }
3796         fastPathCheckNeeded = true;
3797     }
3798 
3799     /**
3800      * Gets the {@link java.math.RoundingMode} used in this DecimalFormat.
3801      *
3802      * @return The {@code RoundingMode} used for this DecimalFormat.
3803      * @see #setRoundingMode(RoundingMode)
3804      * @since 1.6
3805      */
3806     @Override
3807     public RoundingMode getRoundingMode() {
3808         return roundingMode;
3809     }
3810 
3811     /**
3812      * Sets the {@link java.math.RoundingMode} used in this DecimalFormat.
3813      *
3814      * @param roundingMode The {@code RoundingMode} to be used
3815      * @see #getRoundingMode()
3816      * @exception NullPointerException if {@code roundingMode} is null.
3817      * @since 1.6
3818      */
3819     @Override
3820     public void setRoundingMode(RoundingMode roundingMode) {
3821         if (roundingMode == null) {
3822             throw new NullPointerException();
3823         }
3824 
3825         this.roundingMode = roundingMode;
3826         digitList.setRoundingMode(roundingMode);
3827         fastPathCheckNeeded = true;
3828     }
3829 
3830     /**
3831      * Reads the default serializable fields from the stream and performs
3832      * validations and adjustments for older serialized versions. The
3833      * validations and adjustments are:
3834      * <ol>
3835      * <li>
3836      * Verify that the superclass's digit count fields correctly reflect
3837      * the limits imposed on formatting numbers other than
3838      * {@code BigInteger} and {@code BigDecimal} objects. These
3839      * limits are stored in the superclass for serialization compatibility
3840      * with older versions, while the limits for {@code BigInteger} and
3841      * {@code BigDecimal} objects are kept in this class.
3842      * If, in the superclass, the minimum or maximum integer digit count is
3843      * larger than {@code DOUBLE_INTEGER_DIGITS} or if the minimum or
3844      * maximum fraction digit count is larger than
3845      * {@code DOUBLE_FRACTION_DIGITS}, then the stream data is invalid
3846      * and this method throws an {@code InvalidObjectException}.
3847      * <li>
3848      * If {@code serialVersionOnStream} is less than 4, initialize
3849      * {@code roundingMode} to {@link java.math.RoundingMode#HALF_EVEN
3850      * RoundingMode.HALF_EVEN}.  This field is new with version 4.
3851      * <li>
3852      * If {@code serialVersionOnStream} is less than 3, then call
3853      * the setters for the minimum and maximum integer and fraction digits with
3854      * the values of the corresponding superclass getters to initialize the
3855      * fields in this class. The fields in this class are new with version 3.
3856      * <li>
3857      * If {@code serialVersionOnStream} is less than 1, indicating that
3858      * the stream was written by JDK 1.1, initialize
3859      * {@code useExponentialNotation}
3860      * to false, since it was not present in JDK 1.1.
3861      * <li>
3862      * Set {@code serialVersionOnStream} to the maximum allowed value so
3863      * that default serialization will work properly if this object is streamed
3864      * out again.
3865      * </ol>
3866      *
3867      * <p>Stream versions older than 2 will not have the affix pattern variables
3868      * {@code posPrefixPattern} etc.  As a result, they will be initialized
3869      * to {@code null}, which means the affix strings will be taken as
3870      * literal values.  This is exactly what we want, since that corresponds to
3871      * the pre-version-2 behavior.
3872      */
3873     private void readObject(ObjectInputStream stream)
3874          throws IOException, ClassNotFoundException
3875     {
3876         stream.defaultReadObject();
3877         digitList = new DigitList();
3878 
3879         // We force complete fast-path reinitialization when the instance is
3880         // deserialized. See clone() comment on fastPathCheckNeeded.
3881         fastPathCheckNeeded = true;
3882         isFastPath = false;
3883         fastPathData = null;
3884 
3885         if (serialVersionOnStream < 4) {
3886             setRoundingMode(RoundingMode.HALF_EVEN);
3887         } else {
3888             setRoundingMode(getRoundingMode());
3889         }
3890 
3891         // We only need to check the maximum counts because NumberFormat
3892         // .readObject has already ensured that the maximum is greater than the
3893         // minimum count.
3894         if (super.getMaximumIntegerDigits() > DOUBLE_INTEGER_DIGITS ||
3895             super.getMaximumFractionDigits() > DOUBLE_FRACTION_DIGITS) {
3896             throw new InvalidObjectException("Digit count out of range");
3897         }
3898         if (serialVersionOnStream < 3) {
3899             setMaximumIntegerDigits(super.getMaximumIntegerDigits());
3900             setMinimumIntegerDigits(super.getMinimumIntegerDigits());
3901             setMaximumFractionDigits(super.getMaximumFractionDigits());
3902             setMinimumFractionDigits(super.getMinimumFractionDigits());
3903         }
3904         if (serialVersionOnStream < 1) {
3905             // Didn't have exponential fields
3906             useExponentialNotation = false;
3907         }
3908         serialVersionOnStream = currentSerialVersion;
3909     }
3910 
3911     //----------------------------------------------------------------------
3912     // INSTANCE VARIABLES
3913     //----------------------------------------------------------------------
3914 
3915     private transient DigitList digitList = new DigitList();
3916 
3917     /**
3918      * The symbol used as a prefix when formatting positive numbers, e.g. "+".
3919      *
3920      * @serial
3921      * @see #getPositivePrefix
3922      */
3923     private String  positivePrefix = "";
3924 
3925     /**
3926      * The symbol used as a suffix when formatting positive numbers.
3927      * This is often an empty string.
3928      *
3929      * @serial
3930      * @see #getPositiveSuffix
3931      */
3932     private String  positiveSuffix = "";
3933 
3934     /**
3935      * The symbol used as a prefix when formatting negative numbers, e.g. "-".
3936      *
3937      * @serial
3938      * @see #getNegativePrefix
3939      */
3940     private String  negativePrefix = "-";
3941 
3942     /**
3943      * The symbol used as a suffix when formatting negative numbers.
3944      * This is often an empty string.
3945      *
3946      * @serial
3947      * @see #getNegativeSuffix
3948      */
3949     private String  negativeSuffix = "";
3950 
3951     /**
3952      * The prefix pattern for non-negative numbers.  This variable corresponds
3953      * to {@code positivePrefix}.
3954      *
3955      * <p>This pattern is expanded by the method {@code expandAffix()} to
3956      * {@code positivePrefix} to update the latter to reflect changes in
3957      * {@code symbols}.  If this variable is {@code null} then
3958      * {@code positivePrefix} is taken as a literal value that does not
3959      * change when {@code symbols} changes.  This variable is always
3960      * {@code null} for {@code DecimalFormat} objects older than
3961      * stream version 2 restored from stream.
3962      *
3963      * @serial
3964      * @since 1.3
3965      */
3966     private String posPrefixPattern;
3967 
3968     /**
3969      * The suffix pattern for non-negative numbers.  This variable corresponds
3970      * to {@code positiveSuffix}.  This variable is analogous to
3971      * {@code posPrefixPattern}; see that variable for further
3972      * documentation.
3973      *
3974      * @serial
3975      * @since 1.3
3976      */
3977     private String posSuffixPattern;
3978 
3979     /**
3980      * The prefix pattern for negative numbers.  This variable corresponds
3981      * to {@code negativePrefix}.  This variable is analogous to
3982      * {@code posPrefixPattern}; see that variable for further
3983      * documentation.
3984      *
3985      * @serial
3986      * @since 1.3
3987      */
3988     private String negPrefixPattern;
3989 
3990     /**
3991      * The suffix pattern for negative numbers.  This variable corresponds
3992      * to {@code negativeSuffix}.  This variable is analogous to
3993      * {@code posPrefixPattern}; see that variable for further
3994      * documentation.
3995      *
3996      * @serial
3997      * @since 1.3
3998      */
3999     private String negSuffixPattern;
4000 
4001     /**
4002      * The multiplier for use in percent, per mille, etc.
4003      *
4004      * @serial
4005      * @see #getMultiplier
4006      */
4007     private int     multiplier = 1;
4008 
4009     /**
4010      * The number of digits between grouping separators in the integer
4011      * portion of a number.  Must be greater than 0 if
4012      * {@code NumberFormat.groupingUsed} is true.
4013      *
4014      * @serial
4015      * @see #getGroupingSize
4016      * @see java.text.NumberFormat#isGroupingUsed
4017      */
4018     private byte    groupingSize = 3;  // invariant, > 0 if useThousands
4019 
4020     /**
4021      * If true, forces the decimal separator to always appear in a formatted
4022      * number, even if the fractional part of the number is zero.
4023      *
4024      * @serial
4025      * @see #isDecimalSeparatorAlwaysShown
4026      */
4027     private boolean decimalSeparatorAlwaysShown = false;
4028 
4029     /**
4030      * If true, parse returns BigDecimal wherever possible.
4031      *
4032      * @serial
4033      * @see #isParseBigDecimal
4034      * @since 1.5
4035      */
4036     private boolean parseBigDecimal = false;
4037 
4038 
4039     /**
4040      * True if this object represents a currency format.  This determines
4041      * whether the monetary decimal separator is used instead of the normal one.
4042      */
4043     private transient boolean isCurrencyFormat = false;
4044 
4045     /**
4046      * The {@code DecimalFormatSymbols} object used by this format.
4047      * It contains the symbols used to format numbers, e.g. the grouping separator,
4048      * decimal separator, and so on.
4049      *
4050      * @serial
4051      * @see #setDecimalFormatSymbols
4052      * @see java.text.DecimalFormatSymbols
4053      */
4054     private DecimalFormatSymbols symbols = null; // LIU new DecimalFormatSymbols();
4055 
4056     /**
4057      * True to force the use of exponential (i.e. scientific) notation when formatting
4058      * numbers.
4059      *
4060      * @serial
4061      * @since 1.2
4062      */
4063     private boolean useExponentialNotation;  // Newly persistent in the Java 2 platform v.1.2
4064 
4065     /**
4066      * FieldPositions describing the positive prefix String. This is
4067      * lazily created. Use {@code getPositivePrefixFieldPositions}
4068      * when needed.
4069      */
4070     private transient FieldPosition[] positivePrefixFieldPositions;
4071 
4072     /**
4073      * FieldPositions describing the positive suffix String. This is
4074      * lazily created. Use {@code getPositiveSuffixFieldPositions}
4075      * when needed.
4076      */
4077     private transient FieldPosition[] positiveSuffixFieldPositions;
4078 
4079     /**
4080      * FieldPositions describing the negative prefix String. This is
4081      * lazily created. Use {@code getNegativePrefixFieldPositions}
4082      * when needed.
4083      */
4084     private transient FieldPosition[] negativePrefixFieldPositions;
4085 
4086     /**
4087      * FieldPositions describing the negative suffix String. This is
4088      * lazily created. Use {@code getNegativeSuffixFieldPositions}
4089      * when needed.
4090      */
4091     private transient FieldPosition[] negativeSuffixFieldPositions;
4092 
4093     /**
4094      * The minimum number of digits used to display the exponent when a number is
4095      * formatted in exponential notation.  This field is ignored if
4096      * {@code useExponentialNotation} is not true.
4097      *
4098      * @serial
4099      * @since 1.2
4100      */
4101     private byte    minExponentDigits;       // Newly persistent in the Java 2 platform v.1.2
4102 
4103     /**
4104      * The maximum number of digits allowed in the integer portion of a
4105      * {@code BigInteger} or {@code BigDecimal} number.
4106      * {@code maximumIntegerDigits} must be greater than or equal to
4107      * {@code minimumIntegerDigits}.
4108      *
4109      * @serial
4110      * @see #getMaximumIntegerDigits
4111      * @since 1.5
4112      */
4113     private int    maximumIntegerDigits = super.getMaximumIntegerDigits();
4114 
4115     /**
4116      * The minimum number of digits allowed in the integer portion of a
4117      * {@code BigInteger} or {@code BigDecimal} number.
4118      * {@code minimumIntegerDigits} must be less than or equal to
4119      * {@code maximumIntegerDigits}.
4120      *
4121      * @serial
4122      * @see #getMinimumIntegerDigits
4123      * @since 1.5
4124      */
4125     private int    minimumIntegerDigits = super.getMinimumIntegerDigits();
4126 
4127     /**
4128      * The maximum number of digits allowed in the fractional portion of a
4129      * {@code BigInteger} or {@code BigDecimal} number.
4130      * {@code maximumFractionDigits} must be greater than or equal to
4131      * {@code minimumFractionDigits}.
4132      *
4133      * @serial
4134      * @see #getMaximumFractionDigits
4135      * @since 1.5
4136      */
4137     private int    maximumFractionDigits = super.getMaximumFractionDigits();
4138 
4139     /**
4140      * The minimum number of digits allowed in the fractional portion of a
4141      * {@code BigInteger} or {@code BigDecimal} number.
4142      * {@code minimumFractionDigits} must be less than or equal to
4143      * {@code maximumFractionDigits}.
4144      *
4145      * @serial
4146      * @see #getMinimumFractionDigits
4147      * @since 1.5
4148      */
4149     private int    minimumFractionDigits = super.getMinimumFractionDigits();
4150 
4151     /**
4152      * The {@link java.math.RoundingMode} used in this DecimalFormat.
4153      *
4154      * @serial
4155      * @since 1.6
4156      */
4157     private RoundingMode roundingMode = RoundingMode.HALF_EVEN;
4158 
4159     // ------ DecimalFormat fields for fast-path for double algorithm  ------
4160 
4161     /**
4162      * Helper inner utility class for storing the data used in the fast-path
4163      * algorithm. Almost all fields related to fast-path are encapsulated in
4164      * this class.
4165      *
4166      * Any {@code DecimalFormat} instance has a {@code fastPathData}
4167      * reference field that is null unless both the properties of the instance
4168      * are such that the instance is in the "fast-path" state, and a format call
4169      * has been done at least once while in this state.
4170      *
4171      * Almost all fields are related to the "fast-path" state only and don't
4172      * change until one of the instance properties is changed.
4173      *
4174      * {@code firstUsedIndex} and {@code lastFreeIndex} are the only
4175      * two fields that are used and modified while inside a call to
4176      * {@code fastDoubleFormat}.
4177      *
4178      */
4179     private static class FastPathData {
4180         // --- Temporary fields used in fast-path, shared by several methods.
4181 
4182         /** The first unused index at the end of the formatted result. */
4183         int lastFreeIndex;
4184 
4185         /** The first used index at the beginning of the formatted result */
4186         int firstUsedIndex;
4187 
4188         // --- State fields related to fast-path status. Changes due to a
4189         //     property change only. Set by checkAndSetFastPathStatus() only.
4190 
4191         /** Difference between locale zero and default zero representation. */
4192         int  zeroDelta;
4193 
4194         /** Locale char for grouping separator. */
4195         char groupingChar;
4196 
4197         /**  Fixed index position of last integral digit of formatted result */
4198         int integralLastIndex;
4199 
4200         /**  Fixed index position of first fractional digit of formatted result */
4201         int fractionalFirstIndex;
4202 
4203         /** Fractional constants depending on decimal|currency state */
4204         double fractionalScaleFactor;
4205         int fractionalMaxIntBound;
4206 
4207 
4208         /** The char array buffer that will contain the formatted result */
4209         char[] fastPathContainer;
4210 
4211         /** Suffixes recorded as char array for efficiency. */
4212         char[] charsPositivePrefix;
4213         char[] charsNegativePrefix;
4214         char[] charsPositiveSuffix;
4215         char[] charsNegativeSuffix;
4216         boolean positiveAffixesRequired = true;
4217         boolean negativeAffixesRequired = true;
4218     }
4219 
4220     /** The format fast-path status of the instance. Logical state. */
4221     private transient boolean isFastPath = false;
4222 
4223     /** Flag stating need of check and reinit fast-path status on next format call. */
4224     private transient boolean fastPathCheckNeeded = true;
4225 
4226     /** DecimalFormat reference to its FastPathData */
4227     private transient FastPathData fastPathData;
4228 
4229 
4230     //----------------------------------------------------------------------
4231 
4232     static final int currentSerialVersion = 4;
4233 
4234     /**
4235      * The internal serial version which says which version was written.
4236      * Possible values are:
4237      * <ul>
4238      * <li><b>0</b> (default): versions before the Java 2 platform v1.2
4239      * <li><b>1</b>: version for 1.2, which includes the two new fields
4240      *      {@code useExponentialNotation} and
4241      *      {@code minExponentDigits}.
4242      * <li><b>2</b>: version for 1.3 and later, which adds four new fields:
4243      *      {@code posPrefixPattern}, {@code posSuffixPattern},
4244      *      {@code negPrefixPattern}, and {@code negSuffixPattern}.
4245      * <li><b>3</b>: version for 1.5 and later, which adds five new fields:
4246      *      {@code maximumIntegerDigits},
4247      *      {@code minimumIntegerDigits},
4248      *      {@code maximumFractionDigits},
4249      *      {@code minimumFractionDigits}, and
4250      *      {@code parseBigDecimal}.
4251      * <li><b>4</b>: version for 1.6 and later, which adds one new field:
4252      *      {@code roundingMode}.
4253      * </ul>
4254      * @since 1.2
4255      * @serial
4256      */
4257     private int serialVersionOnStream = currentSerialVersion;
4258 
4259     //----------------------------------------------------------------------
4260     // CONSTANTS
4261     //----------------------------------------------------------------------
4262 
4263     // ------ Fast-Path for double Constants ------
4264 
4265     /** Maximum valid integer value for applying fast-path algorithm */
4266     private static final double MAX_INT_AS_DOUBLE = (double) Integer.MAX_VALUE;
4267 
4268     /**
4269      * The digit arrays used in the fast-path methods for collecting digits.
4270      * Using 3 constants arrays of chars ensures a very fast collection of digits
4271      */
4272     private static class DigitArrays {
4273         static final char[] DigitOnes1000 = new char[1000];
4274         static final char[] DigitTens1000 = new char[1000];
4275         static final char[] DigitHundreds1000 = new char[1000];
4276 
4277         // initialize on demand holder class idiom for arrays of digits
4278         static {
4279             int tenIndex = 0;
4280             int hundredIndex = 0;
4281             char digitOne = '0';
4282             char digitTen = '0';
4283             char digitHundred = '0';
4284             for (int i = 0;  i < 1000; i++ ) {
4285 
4286                 DigitOnes1000[i] = digitOne;
4287                 if (digitOne == '9')
4288                     digitOne = '0';
4289                 else
4290                     digitOne++;
4291 
4292                 DigitTens1000[i] = digitTen;
4293                 if (i == (tenIndex + 9)) {
4294                     tenIndex += 10;
4295                     if (digitTen == '9')
4296                         digitTen = '0';
4297                     else
4298                         digitTen++;
4299                 }
4300 
4301                 DigitHundreds1000[i] = digitHundred;
4302                 if (i == (hundredIndex + 99)) {
4303                     digitHundred++;
4304                     hundredIndex += 100;
4305                 }
4306             }
4307         }
4308     }
4309     // ------ Fast-Path for double Constants end ------
4310 
4311     // Constants for characters used in programmatic (unlocalized) patterns.
4312     private static final char       PATTERN_ZERO_DIGIT         = '0';
4313     private static final char       PATTERN_GROUPING_SEPARATOR = ',';
4314     private static final char       PATTERN_DECIMAL_SEPARATOR  = '.';
4315     private static final char       PATTERN_PER_MILLE          = '\u2030';
4316     private static final char       PATTERN_PERCENT            = '%';
4317     private static final char       PATTERN_DIGIT              = '#';
4318     private static final char       PATTERN_SEPARATOR          = ';';
4319     private static final String     PATTERN_EXPONENT           = "E";
4320     private static final char       PATTERN_MINUS              = '-';
4321 
4322     /**
4323      * The CURRENCY_SIGN is the standard Unicode symbol for currency.  It
4324      * is used in patterns and substituted with either the currency symbol,
4325      * or if it is doubled, with the international currency symbol.  If the
4326      * CURRENCY_SIGN is seen in a pattern, then the decimal separator is
4327      * replaced with the monetary decimal separator.
4328      *
4329      * The CURRENCY_SIGN is not localized.
4330      */
4331     private static final char       CURRENCY_SIGN = '\u00A4';
4332 
4333     private static final char       QUOTE = '\'';
4334 
4335     private static FieldPosition[] EmptyFieldPositionArray = new FieldPosition[0];
4336 
4337     // Upper limit on integer and fraction digits for a Java double
4338     static final int DOUBLE_INTEGER_DIGITS  = 309;
4339     static final int DOUBLE_FRACTION_DIGITS = 340;
4340 
4341     // Upper limit on integer and fraction digits for BigDecimal and BigInteger
4342     static final int MAXIMUM_INTEGER_DIGITS  = Integer.MAX_VALUE;
4343     static final int MAXIMUM_FRACTION_DIGITS = Integer.MAX_VALUE;
4344 
4345     // Proclaim JDK 1.1 serial compatibility.
4346     static final long serialVersionUID = 864413376551465018L;
4347 }