Home | History | Annotate | Download | only in text
      1 /*
      2  * Licensed to the Apache Software Foundation (ASF) under one or more
      3  * contributor license agreements.  See the NOTICE file distributed with
      4  * this work for additional information regarding copyright ownership.
      5  * The ASF licenses this file to You under the Apache License, Version 2.0
      6  * (the "License"); you may not use this file except in compliance with
      7  * the License.  You may obtain a copy of the License at
      8  *
      9  *     http://www.apache.org/licenses/LICENSE-2.0
     10  *
     11  * Unless required by applicable law or agreed to in writing, software
     12  * distributed under the License is distributed on an "AS IS" BASIS,
     13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     14  * See the License for the specific language governing permissions and
     15  * limitations under the License.
     16  */
     17 
     18 package java.text;
     19 
     20 import java.io.IOException;
     21 import java.io.ObjectInputStream;
     22 import java.io.ObjectOutputStream;
     23 import java.io.ObjectStreamField;
     24 import java.math.BigDecimal;
     25 import java.math.BigInteger;
     26 import java.math.RoundingMode;
     27 import java.util.Currency;
     28 import java.util.Locale;
     29 import libcore.icu.LocaleData;
     30 import libcore.icu.NativeDecimalFormat;
     31 
     32 /**
     33  * A concrete subclass of {@link NumberFormat} that formats decimal numbers. It
     34  * has a variety of features designed to make it possible to parse and format
     35  * numbers in any locale, including support for Western, Arabic, or Indic
     36  * digits. It also supports different flavors of numbers, including integers
     37  * ("123"), fixed-point numbers ("123.4"), scientific notation ("1.23E4"),
     38  * percentages ("12%"), and currency amounts ("$123"). All of these flavors can
     39  * be easily localized.
     40  * <p>
     41  * <strong>This is an enhanced version of {@code DecimalFormat} that is based on
     42  * the standard version in the RI. New or changed functionality is labeled
     43  * <strong><font color="red">NEW</font></strong>.</strong>
     44  * <p>
     45  * To obtain a {@link NumberFormat} for a specific locale (including the default
     46  * locale), call one of {@code NumberFormat}'s factory methods such as
     47  * {@code NumberFormat.getInstance}. Do not call the {@code DecimalFormat}
     48  * constructors directly, unless you know what you are doing, since the
     49  * {@link NumberFormat} factory methods may return subclasses other than
     50  * {@code DecimalFormat}. If you need to customize the format object, do
     51  * something like this: <blockquote>
     52  *
     53  * <pre>
     54  * NumberFormat f = NumberFormat.getInstance(loc);
     55  * if (f instanceof DecimalFormat) {
     56  *     ((DecimalFormat)f).setDecimalSeparatorAlwaysShown(true);
     57  * }
     58  * </pre>
     59  *
     60  * </blockquote>
     61  *
     62  * <h4>Patterns</h4>
     63  * <p>
     64  * A {@code DecimalFormat} consists of a <em>pattern</em> and a set of
     65  * <em>symbols</em>. The pattern may be set directly using
     66  * {@link #applyPattern(String)}, or indirectly using other API methods which
     67  * manipulate aspects of the pattern, such as the minimum number of integer
     68  * digits. The symbols are stored in a {@link DecimalFormatSymbols} object. When
     69  * using the {@link NumberFormat} factory methods, the pattern and symbols are
     70  * read from ICU's locale data.
     71  * <h4>Special Pattern Characters</h4>
     72  * <p>
     73  * Many characters in a pattern are taken literally; they are matched during
     74  * parsing and are written out unchanged during formatting. On the other hand,
     75  * special characters stand for other characters, strings, or classes of
     76  * characters. For example, the '#' character is replaced by a localized digit.
     77  * Often the replacement character is the same as the pattern character; in the
     78  * U.S. locale, the ',' grouping character is replaced by ','. However, the
     79  * replacement is still happening, and if the symbols are modified, the grouping
     80  * character changes. Some special characters affect the behavior of the
     81  * formatter by their presence; for example, if the percent character is seen,
     82  * then the value is multiplied by 100 before being displayed.
     83  * <p>
     84  * To insert a special character in a pattern as a literal, that is, without any
     85  * special meaning, the character must be quoted. There are some exceptions to
     86  * this which are noted below.
     87  * <p>
     88  * The characters listed here are used in non-localized patterns. Localized
     89  * patterns use the corresponding characters taken from this formatter's
     90  * {@link DecimalFormatSymbols} object instead, and these characters lose their
     91  * special status. Two exceptions are the currency sign and quote, which are not
     92  * localized.
     93  * <blockquote> <table border="0" cellspacing="3" cellpadding="0" summary="Chart
     94  * showing symbol, location, localized, and meaning.">
     95  * <tr bgcolor="#ccccff">
     96  * <th align="left">Symbol</th>
     97  * <th align="left">Location</th>
     98  * <th align="left">Localized?</th>
     99  * <th align="left">Meaning</th>
    100  * </tr>
    101  * <tr valign="top">
    102  * <td>{@code 0}</td>
    103  * <td>Number</td>
    104  * <td>Yes</td>
    105  * <td>Digit.</td>
    106  * </tr>
    107  * <tr valign="top">
    108  * <td>{@code @}</td>
    109  * <td>Number</td>
    110  * <td>No</td>
    111  * <td><strong><font color="red">NEW</font>&nbsp;</strong> Significant
    112  * digit.</td>
    113  * </tr>
    114  * <tr valign="top" bgcolor="#eeeeff">
    115  * <td>{@code #}</td>
    116  * <td>Number</td>
    117  * <td>Yes</td>
    118  * <td>Digit, leading zeroes are not shown.</td>
    119  * </tr>
    120  * <tr valign="top">
    121  * <td>{@code .}</td>
    122  * <td>Number</td>
    123  * <td>Yes</td>
    124  * <td>Decimal separator or monetary decimal separator.</td>
    125  * </tr>
    126  * <tr valign="top" bgcolor="#eeeeff">
    127  * <td>{@code -}</td>
    128  * <td>Number</td>
    129  * <td>Yes</td>
    130  * <td>Minus sign.</td>
    131  * </tr>
    132  * <tr valign="top">
    133  * <td>{@code ,}</td>
    134  * <td>Number</td>
    135  * <td>Yes</td>
    136  * <td>Grouping separator.</td>
    137  * </tr>
    138  * <tr valign="top" bgcolor="#eeeeff">
    139  * <td>{@code E}</td>
    140  * <td>Number</td>
    141  * <td>Yes</td>
    142  * <td>Separates mantissa and exponent in scientific notation.
    143  * <em>Does not need to be quoted in prefix or suffix.</em></td>
    144  * </tr>
    145  * <tr valign="top">
    146  * <td>{@code +}</td>
    147  * <td>Exponent</td>
    148  * <td>Yes</td>
    149  * <td><strong><font color="red">NEW</font>&nbsp;</strong> Prefix
    150  * positive exponents with localized plus sign.
    151  * <em>Does not need to be quoted in prefix or suffix.</em></td>
    152  * </tr>
    153  * <tr valign="top" bgcolor="#eeeeff">
    154  * <td>{@code ;}</td>
    155  * <td>Subpattern boundary</td>
    156  * <td>Yes</td>
    157  * <td>Separates positive and negative subpatterns.</td>
    158  * </tr>
    159  * <tr valign="top">
    160  * <td>{@code %}</td>
    161  * <td>Prefix or suffix</td>
    162  * <td>Yes</td>
    163  * <td>Multiply by 100 and show as percentage.</td>
    164  * </tr>
    165  * <tr valign="top" bgcolor="#eeeeff">
    166  * <td>{@code \u2030} ({@code \u005Cu2030})</td>
    167  * <td>Prefix or suffix</td>
    168  * <td>Yes</td>
    169  * <td>Multiply by 1000 and show as per mille.</td>
    170  * </tr>
    171  * <tr valign="top">
    172  * <td>{@code \u00A4} ({@code \u005Cu00A4})</td>
    173  * <td>Prefix or suffix</td>
    174  * <td>No</td>
    175  * <td>Currency sign, replaced by currency symbol. If doubled, replaced by
    176  * international currency symbol. If present in a pattern, the monetary decimal
    177  * separator is used instead of the decimal separator.</td>
    178  * </tr>
    179  * <tr valign="top" bgcolor="#eeeeff">
    180  * <td>{@code '}</td>
    181  * <td>Prefix or suffix</td>
    182  * <td>No</td>
    183  * <td>Used to quote special characters in a prefix or suffix, for example,
    184  * {@code "'#'#"} formats 123 to {@code "#123"}. To create a single quote
    185  * itself, use two in a row: {@code "# o''clock"}.</td>
    186  * </tr>
    187  * <tr valign="top">
    188  * <td>{@code *}</td>
    189  * <td>Prefix or suffix boundary</td>
    190  * <td>Yes</td>
    191  * <td><strong><font color="red">NEW</font>&nbsp;</strong> Pad escape,
    192  * precedes pad character. </td>
    193  * </tr>
    194  * </table> </blockquote>
    195  * <p>
    196  * A {@code DecimalFormat} pattern contains a positive and negative subpattern,
    197  * for example, "#,##0.00;(#,##0.00)". Each subpattern has a prefix, a numeric
    198  * part and a suffix. If there is no explicit negative subpattern, the negative
    199  * subpattern is the localized minus sign prefixed to the positive subpattern.
    200  * That is, "0.00" alone is equivalent to "0.00;-0.00". If there is an explicit
    201  * negative subpattern, it serves only to specify the negative prefix and
    202  * suffix; the number of digits, minimal digits, and other characteristics are
    203  * ignored in the negative subpattern. This means that "#,##0.0#;(#)" produces
    204  * precisely the same result as "#,##0.0#;(#,##0.0#)".
    205  * <p>
    206  * The prefixes, suffixes, and various symbols used for infinity, digits,
    207  * thousands separators, decimal separators, etc. may be set to arbitrary
    208  * values, and they will appear properly during formatting. However, care must
    209  * be taken that the symbols and strings do not conflict, or parsing will be
    210  * unreliable. For example, either the positive and negative prefixes or the
    211  * suffixes must be distinct for {@link #parse} to be able to distinguish
    212  * positive from negative values. Another example is that the decimal separator
    213  * and thousands separator should be distinct characters, or parsing will be
    214  * impossible.
    215  * <p>
    216  * The <em>grouping separator</em> is a character that separates clusters of
    217  * integer digits to make large numbers more legible. It is commonly used for
    218  * thousands, but in some locales it separates ten-thousands. The <em>grouping
    219  * size</em>
    220  * is the number of digits between the grouping separators, such as 3 for
    221  * "100,000,000" or 4 for "1 0000 0000". There are actually two different
    222  * grouping sizes: One used for the least significant integer digits, the
    223  * <em>primary grouping size</em>, and one used for all others, the
    224  * <em>secondary grouping size</em>. In most locales these are the same, but
    225  * sometimes they are different. For example, if the primary grouping interval
    226  * is 3, and the secondary is 2, then this corresponds to the pattern
    227  * "#,##,##0", and the number 123456789 is formatted as "12,34,56,789". If a
    228  * pattern contains multiple grouping separators, the interval between the last
    229  * one and the end of the integer defines the primary grouping size, and the
    230  * interval between the last two defines the secondary grouping size. All others
    231  * are ignored, so "#,##,###,####", "###,###,####" and "##,#,###,####" produce
    232  * the same result.
    233  * <p>
    234  * Illegal patterns, such as "#.#.#" or "#.###,###", will cause
    235  * {@code DecimalFormat} to throw an {@link IllegalArgumentException} with a
    236  * message that describes the problem.
    237  * <h4>Pattern BNF</h4>
    238  *
    239  * <pre>
    240  * pattern    := subpattern (';' subpattern)?
    241  * subpattern := prefix? number exponent? suffix?
    242  * number     := (integer ('.' fraction)?) | sigDigits
    243  * prefix     := '\\u0000'..'\\uFFFD' - specialCharacters
    244  * suffix     := '\\u0000'..'\\uFFFD' - specialCharacters
    245  * integer    := '#'* '0'* '0'
    246  * fraction   := '0'* '#'*
    247  * sigDigits  := '#'* '@' '@'* '#'*
    248  * exponent   := 'E' '+'? '0'* '0'
    249  * padSpec    := '*' padChar
    250  * padChar    := '\\u0000'..'\\uFFFD' - quote
    251  *
    252  * Notation:
    253  *   X*       0 or more instances of X
    254  *   X?       0 or 1 instances of X
    255  *   X|Y      either X or Y
    256  *   C..D     any character from C up to D, inclusive
    257  *   S-T      characters in S, except those in T
    258  * </pre>
    259  *
    260  * The first subpattern is for positive numbers. The second (optional)
    261  * subpattern is for negative numbers.
    262  * <p>
    263  * Not indicated in the BNF syntax above:
    264  * <ul>
    265  * <li>The grouping separator ',' can occur inside the integer and sigDigits
    266  * elements, between any two pattern characters of that element, as long as the
    267  * integer or sigDigits element is not followed by the exponent element.
    268  * <li><font color="red"><strong>NEW</strong>&nbsp;</font> Two
    269  * grouping intervals are recognized: The one between the decimal point and the
    270  * first grouping symbol and the one between the first and second grouping
    271  * symbols. These intervals are identical in most locales, but in some locales
    272  * they differ. For example, the pattern &quot;#,##,###&quot; formats the number
    273  * 123456789 as &quot;12,34,56,789&quot;.</li>
    274  * <li> <strong><font color="red">NEW</font>&nbsp;</strong> The pad
    275  * specifier {@code padSpec} may appear before the prefix, after the prefix,
    276  * before the suffix, after the suffix or not at all.
    277  * </ul>
    278  * <h4>Parsing</h4>
    279  * <p>
    280  * {@code DecimalFormat} parses all Unicode characters that represent decimal
    281  * digits, as defined by {@link Character#digit(int, int)}. In addition,
    282  * {@code DecimalFormat} also recognizes as digits the ten consecutive
    283  * characters starting with the localized zero digit defined in the
    284  * {@link DecimalFormatSymbols} object. During formatting, the
    285  * {@link DecimalFormatSymbols}-based digits are written out.
    286  * <p>
    287  * During parsing, grouping separators are ignored.
    288  * <p>
    289  * If {@link #parse(String, ParsePosition)} fails to parse a string, it returns
    290  * {@code null} and leaves the parse position unchanged.
    291  * <h4>Formatting</h4>
    292  * <p>
    293  * Formatting is guided by several parameters, all of which can be specified
    294  * either using a pattern or using the API. The following description applies to
    295  * formats that do not use <a href="#sci">scientific notation</a> or <a
    296  * href="#sigdig">significant digits</a>.
    297  * <ul>
    298  * <li>If the number of actual integer digits exceeds the
    299  * <em>maximum integer digits</em>, then only the least significant digits
    300  * are shown. For example, 1997 is formatted as "97" if maximum integer digits
    301  * is set to 2.
    302  * <li>If the number of actual integer digits is less than the
    303  * <em>minimum integer digits</em>, then leading zeros are added. For
    304  * example, 1997 is formatted as "01997" if minimum integer digits is set to 5.
    305  * <li>If the number of actual fraction digits exceeds the <em>maximum
    306  * fraction digits</em>,
    307  * then half-even rounding is performed to the maximum fraction digits. For
    308  * example, 0.125 is formatted as "0.12" if the maximum fraction digits is 2.
    309  * <li>If the number of actual fraction digits is less than the
    310  * <em>minimum fraction digits</em>, then trailing zeros are added. For
    311  * example, 0.125 is formatted as "0.1250" if the minimum fraction digits is set
    312  * to 4.
    313  * <li>Trailing fractional zeros are not displayed if they occur <em>j</em>
    314  * positions after the decimal, where <em>j</em> is less than the maximum
    315  * fraction digits. For example, 0.10004 is formatted as "0.1" if the maximum
    316  * fraction digits is four or less.
    317  * </ul>
    318  * <p>
    319  * <strong>Special Values</strong>
    320  * <p>
    321  * {@code NaN} is represented as a single character, typically
    322  * {@code \u005cuFFFD}. This character is determined by the
    323  * {@link DecimalFormatSymbols} object. This is the only value for which the
    324  * prefixes and suffixes are not used.
    325  * <p>
    326  * Infinity is represented as a single character, typically {@code \u005cu221E},
    327  * with the positive or negative prefixes and suffixes applied. The infinity
    328  * character is determined by the {@link DecimalFormatSymbols} object. <a
    329  * name="sci">
    330  * <h4>Scientific Notation</h4>
    331  * </a>
    332  * <p>
    333  * Numbers in scientific notation are expressed as the product of a mantissa and
    334  * a power of ten, for example, 1234 can be expressed as 1.234 x 10<sup>3</sup>.
    335  * The mantissa is typically in the half-open interval [1.0, 10.0) or sometimes
    336  * [0.0, 1.0), but it does not need to be. {@code DecimalFormat} supports
    337  * arbitrary mantissas. {@code DecimalFormat} can be instructed to use
    338  * scientific notation through the API or through the pattern. In a pattern, the
    339  * exponent character immediately followed by one or more digit characters
    340  * indicates scientific notation. Example: "0.###E0" formats the number 1234 as
    341  * "1.234E3".
    342  * <ul>
    343  * <li>The number of digit characters after the exponent character gives the
    344  * minimum exponent digit count. There is no maximum. Negative exponents are
    345  * formatted using the localized minus sign, <em>not</em> the prefix and
    346  * suffix from the pattern. This allows patterns such as "0.###E0 m/s". To
    347  * prefix positive exponents with a localized plus sign, specify '+' between the
    348  * exponent and the digits: "0.###E+0" will produce formats "1E+1", "1E+0",
    349  * "1E-1", etc. (In localized patterns, use the localized plus sign rather than
    350  * '+'.)
    351  * <li>The minimum number of integer digits is achieved by adjusting the
    352  * exponent. Example: 0.00123 formatted with "00.###E0" yields "12.3E-4". This
    353  * only happens if there is no maximum number of integer digits. If there is a
    354  * maximum, then the minimum number of integer digits is fixed at one.
    355  * <li>The maximum number of integer digits, if present, specifies the exponent
    356  * grouping. The most common use of this is to generate <em>engineering
    357  * notation</em>,
    358  * in which the exponent is a multiple of three, e.g., "##0.###E0". The number
    359  * 12345 is formatted using "##0.###E0" as "12.345E3".
    360  * <li>When using scientific notation, the formatter controls the digit counts
    361  * using significant digits logic. The maximum number of significant digits
    362  * limits the total number of integer and fraction digits that will be shown in
    363  * the mantissa; it does not affect parsing. For example, 12345 formatted with
    364  * "##0.##E0" is "12.3E3". See the section on significant digits for more
    365  * details.
    366  * <li>The number of significant digits shown is determined as follows: If no
    367  * significant digits are used in the pattern then the minimum number of
    368  * significant digits shown is one, the maximum number of significant digits
    369  * shown is the sum of the <em>minimum integer</em> and
    370  * <em>maximum fraction</em> digits, and it is unaffected by the maximum
    371  * integer digits. If this sum is zero, then all significant digits are shown.
    372  * If significant digits are used in the pattern then the number of integer
    373  * digits is fixed at one and there is no exponent grouping.
    374  * <li>Exponential patterns may not contain grouping separators.
    375  * </ul>
    376  * <a name="sigdig">
    377  * <h4> <strong><font color="red">NEW</font>&nbsp;</strong> Significant
    378  * Digits</h4>
    379  * <p>
    380  * </a> {@code DecimalFormat} has two ways of controlling how many digits are
    381  * shown: (a) significant digit counts or (b) integer and fraction digit counts.
    382  * Integer and fraction digit counts are described above. When a formatter uses
    383  * significant digits counts, the number of integer and fraction digits is not
    384  * specified directly, and the formatter settings for these counts are ignored.
    385  * Instead, the formatter uses as many integer and fraction digits as required
    386  * to display the specified number of significant digits.
    387  * <h5>Examples:</h5>
    388  * <blockquote> <table border=0 cellspacing=3 cellpadding=0>
    389  * <tr bgcolor="#ccccff">
    390  * <th align="left">Pattern</th>
    391  * <th align="left">Minimum significant digits</th>
    392  * <th align="left">Maximum significant digits</th>
    393  * <th align="left">Number</th>
    394  * <th align="left">Output of format()</th>
    395  * </tr>
    396  * <tr valign="top">
    397  * <td>{@code @@@}
    398  * <td>3</td>
    399  * <td>3</td>
    400  * <td>12345</td>
    401  * <td>{@code 12300}</td>
    402  * </tr>
    403  * <tr valign="top" bgcolor="#eeeeff">
    404  * <td>{@code @@@}</td>
    405  * <td>3</td>
    406  * <td>3</td>
    407  * <td>0.12345</td>
    408  * <td>{@code 0.123}</td>
    409  * </tr>
    410  * <tr valign="top">
    411  * <td>{@code @@##}</td>
    412  * <td>2</td>
    413  * <td>4</td>
    414  * <td>3.14159</td>
    415  * <td>{@code 3.142}</td>
    416  * </tr>
    417  * <tr valign="top" bgcolor="#eeeeff">
    418  * <td>{@code @@##}</td>
    419  * <td>2</td>
    420  * <td>4</td>
    421  * <td>1.23004</td>
    422  * <td>{@code 1.23}</td>
    423  * </tr>
    424  * </table> </blockquote>
    425  * <ul>
    426  * <li>Significant digit counts may be expressed using patterns that specify a
    427  * minimum and maximum number of significant digits. These are indicated by the
    428  * {@code '@'} and {@code '#'} characters. The minimum number of significant
    429  * digits is the number of {@code '@'} characters. The maximum number of
    430  * significant digits is the number of {@code '@'} characters plus the number of
    431  * {@code '#'} characters following on the right. For example, the pattern
    432  * {@code "@@@"} indicates exactly 3 significant digits. The pattern
    433  * {@code "@##"} indicates from 1 to 3 significant digits. Trailing zero digits
    434  * to the right of the decimal separator are suppressed after the minimum number
    435  * of significant digits have been shown. For example, the pattern {@code "@##"}
    436  * formats the number 0.1203 as {@code "0.12"}.
    437  * <li>If a pattern uses significant digits, it may not contain a decimal
    438  * separator, nor the {@code '0'} pattern character. Patterns such as
    439  * {@code "@00"} or {@code "@.###"} are disallowed.
    440  * <li>Any number of {@code '#'} characters may be prepended to the left of the
    441  * leftmost {@code '@'} character. These have no effect on the minimum and
    442  * maximum significant digit counts, but may be used to position grouping
    443  * separators. For example, {@code "#,#@#"} indicates a minimum of one
    444  * significant digit, a maximum of two significant digits, and a grouping size
    445  * of three.
    446  * <li>In order to enable significant digits formatting, use a pattern
    447  * containing the {@code '@'} pattern character.
    448  * <li>In order to disable significant digits formatting, use a pattern that
    449  * does not contain the {@code '@'} pattern character.
    450  * <li>The number of significant digits has no effect on parsing.
    451  * <li>Significant digits may be used together with exponential notation. Such
    452  * patterns are equivalent to a normal exponential pattern with a minimum and
    453  * maximum integer digit count of one, a minimum fraction digit count of the
    454  * number of '@' characters in the pattern - 1, and a maximum fraction digit
    455  * count of the number of '@' and '#' characters in the pattern - 1. For
    456  * example, the pattern {@code "@@###E0"} is equivalent to {@code "0.0###E0"}.
    457  * <li>If significant digits are in use then the integer and fraction digit
    458  * counts, as set via the API, are ignored.
    459  * </ul>
    460  * <h4> <strong><font color="red">NEW</font>&nbsp;</strong> Padding</h4>
    461  * <p>
    462  * {@code DecimalFormat} supports padding the result of {@code format} to a
    463  * specific width. Padding may be specified either through the API or through
    464  * the pattern syntax. In a pattern, the pad escape character followed by a
    465  * single pad character causes padding to be parsed and formatted. The pad
    466  * escape character is '*' in unlocalized patterns. For example,
    467  * {@code "$*x#,##0.00"} formats 123 to {@code "$xx123.00"}, and 1234 to
    468  * {@code "$1,234.00"}.
    469  * <ul>
    470  * <li>When padding is in effect, the width of the positive subpattern,
    471  * including prefix and suffix, determines the format width. For example, in the
    472  * pattern {@code "* #0 o''clock"}, the format width is 10.</li>
    473  * <li>The width is counted in 16-bit code units (Java {@code char}s).</li>
    474  * <li>Some parameters which usually do not matter have meaning when padding is
    475  * used, because the pattern width is significant with padding. In the pattern "*
    476  * ##,##,#,##0.##", the format width is 14. The initial characters "##,##," do
    477  * not affect the grouping size or maximum integer digits, but they do affect
    478  * the format width.</li>
    479  * <li>Padding may be inserted at one of four locations: before the prefix,
    480  * after the prefix, before the suffix or after the suffix. If padding is
    481  * specified in any other location, {@link #applyPattern} throws an {@link
    482  * IllegalArgumentException}. If there is no prefix, before the prefix and after
    483  * the prefix are equivalent, likewise for the suffix.</li>
    484  * <li>When specified in a pattern, the 16-bit {@code char} immediately
    485  * following the pad escape is the pad character. This may be any character,
    486  * including a special pattern character. That is, the pad escape
    487  * <em>escapes</em> the following character. If there is no character after
    488  * the pad escape, then the pattern is illegal.</li>
    489  * </ul>
    490  * <h4>Synchronization</h4>
    491  * <p>
    492  * {@code DecimalFormat} objects are not synchronized. Multiple threads should
    493  * not access one formatter concurrently.
    494  *
    495  * @see Format
    496  * @see NumberFormat
    497  */
    498 public class DecimalFormat extends NumberFormat {
    499 
    500     private static final long serialVersionUID = 864413376551465018L;
    501 
    502     private transient DecimalFormatSymbols symbols;
    503 
    504     private transient NativeDecimalFormat ndf;
    505 
    506     private transient RoundingMode roundingMode = RoundingMode.HALF_EVEN;
    507 
    508     /**
    509      * Constructs a new {@code DecimalFormat} for formatting and parsing numbers
    510      * for the user's default locale.
    511      * See "<a href="../util/Locale.html#default_locale">Be wary of the default locale</a>".
    512      */
    513     public DecimalFormat() {
    514         Locale locale = Locale.getDefault();
    515         this.symbols = new DecimalFormatSymbols(locale);
    516         initNative(LocaleData.get(locale).numberPattern);
    517     }
    518 
    519     /**
    520      * Constructs a new {@code DecimalFormat} using the specified non-localized
    521      * pattern and the {@code DecimalFormatSymbols} for the user's default Locale.
    522      * See "<a href="../util/Locale.html#default_locale">Be wary of the default locale</a>".
    523      * @param pattern
    524      *            the non-localized pattern.
    525      * @throws IllegalArgumentException
    526      *            if the pattern cannot be parsed.
    527      */
    528     public DecimalFormat(String pattern) {
    529         this(pattern, Locale.getDefault());
    530     }
    531 
    532     /**
    533      * Constructs a new {@code DecimalFormat} using the specified non-localized
    534      * pattern and {@code DecimalFormatSymbols}.
    535      *
    536      * @param pattern
    537      *            the non-localized pattern.
    538      * @param value
    539      *            the DecimalFormatSymbols.
    540      * @throws IllegalArgumentException
    541      *            if the pattern cannot be parsed.
    542      */
    543     public DecimalFormat(String pattern, DecimalFormatSymbols value) {
    544         this.symbols = (DecimalFormatSymbols) value.clone();
    545         initNative(pattern);
    546     }
    547 
    548     // Used by NumberFormat.getInstance because cloning DecimalFormatSymbols is slow.
    549     DecimalFormat(String pattern, Locale locale) {
    550         this.symbols = new DecimalFormatSymbols(locale);
    551         initNative(pattern);
    552     }
    553 
    554     private void initNative(String pattern) {
    555         try {
    556             this.ndf = new NativeDecimalFormat(pattern, symbols);
    557         } catch (IllegalArgumentException ex) {
    558             throw new IllegalArgumentException(pattern);
    559         }
    560         super.setMaximumFractionDigits(ndf.getMaximumFractionDigits());
    561         super.setMaximumIntegerDigits(ndf.getMaximumIntegerDigits());
    562         super.setMinimumFractionDigits(ndf.getMinimumFractionDigits());
    563         super.setMinimumIntegerDigits(ndf.getMinimumIntegerDigits());
    564     }
    565 
    566     /**
    567      * Changes the pattern of this decimal format to the specified pattern which
    568      * uses localized pattern characters.
    569      *
    570      * @param pattern
    571      *            the localized pattern.
    572      * @throws IllegalArgumentException
    573      *            if the pattern cannot be parsed.
    574      */
    575     public void applyLocalizedPattern(String pattern) {
    576         ndf.applyLocalizedPattern(pattern);
    577     }
    578 
    579     /**
    580      * Changes the pattern of this decimal format to the specified pattern which
    581      * uses non-localized pattern characters.
    582      *
    583      * @param pattern
    584      *            the non-localized pattern.
    585      * @throws IllegalArgumentException
    586      *            if the pattern cannot be parsed.
    587      */
    588     public void applyPattern(String pattern) {
    589         ndf.applyPattern(pattern);
    590     }
    591 
    592     /**
    593      * Returns a new instance of {@code DecimalFormat} with the same pattern and
    594      * properties.
    595      */
    596     @Override
    597     public Object clone() {
    598         DecimalFormat clone = (DecimalFormat) super.clone();
    599         clone.ndf = (NativeDecimalFormat) ndf.clone();
    600         clone.symbols = (DecimalFormatSymbols) symbols.clone();
    601         return clone;
    602     }
    603 
    604     /**
    605      * Compares the specified object to this decimal format and indicates if
    606      * they are equal. In order to be equal, {@code object} must be an instance
    607      * of {@code DecimalFormat} with the same pattern and properties.
    608      *
    609      * @param object
    610      *            the object to compare with this object.
    611      * @return {@code true} if the specified object is equal to this decimal
    612      *         format; {@code false} otherwise.
    613      * @see #hashCode
    614      */
    615     @Override
    616     public boolean equals(Object object) {
    617         if (this == object) {
    618             return true;
    619         }
    620         if (!(object instanceof DecimalFormat)) {
    621             return false;
    622         }
    623         DecimalFormat other = (DecimalFormat) object;
    624         return (this.ndf == null ? other.ndf == null : this.ndf.equals(other.ndf)) &&
    625                 getDecimalFormatSymbols().equals(other.getDecimalFormatSymbols());
    626     }
    627 
    628     /**
    629      * Formats the specified object using the rules of this decimal format and
    630      * returns an {@code AttributedCharacterIterator} with the formatted number
    631      * and attributes.
    632      *
    633      * @param object
    634      *            the object to format.
    635      * @return an AttributedCharacterIterator with the formatted number and
    636      *         attributes.
    637      * @throws IllegalArgumentException
    638      *             if {@code object} cannot be formatted by this format.
    639      * @throws NullPointerException
    640      *             if {@code object} is {@code null}.
    641      */
    642     @Override
    643     public AttributedCharacterIterator formatToCharacterIterator(Object object) {
    644         if (object == null) {
    645             throw new NullPointerException("object == null");
    646         }
    647         return ndf.formatToCharacterIterator(object);
    648     }
    649 
    650     private void checkBufferAndFieldPosition(StringBuffer buffer, FieldPosition position) {
    651         if (buffer == null) {
    652             throw new NullPointerException("buffer == null");
    653         }
    654         if (position == null) {
    655             throw new NullPointerException("position == null");
    656         }
    657     }
    658 
    659     @Override
    660     public StringBuffer format(double value, StringBuffer buffer, FieldPosition position) {
    661         checkBufferAndFieldPosition(buffer, position);
    662         // All float/double/Float/Double formatting ends up here...
    663         if (roundingMode == RoundingMode.UNNECESSARY) {
    664             // ICU4C doesn't support this rounding mode, so we have to fake it.
    665             try {
    666                 setRoundingMode(RoundingMode.UP);
    667                 String upResult = format(value, new StringBuffer(), new FieldPosition(0)).toString();
    668                 setRoundingMode(RoundingMode.DOWN);
    669                 String downResult = format(value, new StringBuffer(), new FieldPosition(0)).toString();
    670                 if (!upResult.equals(downResult)) {
    671                     throw new ArithmeticException("rounding mode UNNECESSARY but rounding required");
    672                 }
    673             } finally {
    674                 setRoundingMode(RoundingMode.UNNECESSARY);
    675             }
    676         }
    677         buffer.append(ndf.formatDouble(value, position));
    678         return buffer;
    679     }
    680 
    681     @Override
    682     public StringBuffer format(long value, StringBuffer buffer, FieldPosition position) {
    683         checkBufferAndFieldPosition(buffer, position);
    684         buffer.append(ndf.formatLong(value, position));
    685         return buffer;
    686     }
    687 
    688     @Override
    689     public final StringBuffer format(Object number, StringBuffer buffer, FieldPosition position) {
    690         checkBufferAndFieldPosition(buffer, position);
    691         if (number instanceof BigInteger) {
    692             BigInteger bigInteger = (BigInteger) number;
    693             char[] chars = (bigInteger.bitLength() < 64)
    694                     ? ndf.formatLong(bigInteger.longValue(), position)
    695                     : ndf.formatBigInteger(bigInteger, position);
    696             buffer.append(chars);
    697             return buffer;
    698         } else if (number instanceof BigDecimal) {
    699             buffer.append(ndf.formatBigDecimal((BigDecimal) number, position));
    700             return buffer;
    701         }
    702         return super.format(number, buffer, position);
    703     }
    704 
    705     /**
    706      * Returns the {@code DecimalFormatSymbols} used by this decimal format.
    707      *
    708      * @return a copy of the {@code DecimalFormatSymbols} used by this decimal
    709      *         format.
    710      */
    711     public DecimalFormatSymbols getDecimalFormatSymbols() {
    712         return (DecimalFormatSymbols) symbols.clone();
    713     }
    714 
    715     /**
    716      * Returns the currency used by this decimal format.
    717      *
    718      * @return the currency used by this decimal format.
    719      * @see DecimalFormatSymbols#getCurrency()
    720      */
    721     @Override
    722     public Currency getCurrency() {
    723         return symbols.getCurrency();
    724     }
    725 
    726     /**
    727      * Returns the number of digits grouped together by the grouping separator.
    728      * This only allows to get the primary grouping size. There is no API to get
    729      * the secondary grouping size.
    730      *
    731      * @return the number of digits grouped together.
    732      */
    733     public int getGroupingSize() {
    734         return ndf.getGroupingSize();
    735     }
    736 
    737     /**
    738      * Returns the multiplier which is applied to the number before formatting
    739      * or after parsing.
    740      *
    741      * @return the multiplier.
    742      */
    743     public int getMultiplier() {
    744         return ndf.getMultiplier();
    745     }
    746 
    747     /**
    748      * Returns the prefix which is formatted or parsed before a negative number.
    749      *
    750      * @return the negative prefix.
    751      */
    752     public String getNegativePrefix() {
    753         return ndf.getNegativePrefix();
    754     }
    755 
    756     /**
    757      * Returns the suffix which is formatted or parsed after a negative number.
    758      *
    759      * @return the negative suffix.
    760      */
    761     public String getNegativeSuffix() {
    762         return ndf.getNegativeSuffix();
    763     }
    764 
    765     /**
    766      * Returns the prefix which is formatted or parsed before a positive number.
    767      *
    768      * @return the positive prefix.
    769      */
    770     public String getPositivePrefix() {
    771         return ndf.getPositivePrefix();
    772     }
    773 
    774     /**
    775      * Returns the suffix which is formatted or parsed after a positive number.
    776      *
    777      * @return the positive suffix.
    778      */
    779     public String getPositiveSuffix() {
    780         return ndf.getPositiveSuffix();
    781     }
    782 
    783     @Override
    784     public int hashCode() {
    785         return getPositivePrefix().hashCode();
    786     }
    787 
    788     /**
    789      * Indicates whether the decimal separator is shown when there are no
    790      * fractional digits.
    791      *
    792      * @return {@code true} if the decimal separator should always be formatted;
    793      *         {@code false} otherwise.
    794      */
    795     public boolean isDecimalSeparatorAlwaysShown() {
    796         return ndf.isDecimalSeparatorAlwaysShown();
    797     }
    798 
    799     /**
    800      * This value indicates whether the return object of the parse operation is
    801      * of type {@code BigDecimal}. This value defaults to {@code false}.
    802      *
    803      * @return {@code true} if parse always returns {@code BigDecimals},
    804      *         {@code false} if the type of the result is {@code Long} or
    805      *         {@code Double}.
    806      */
    807     public boolean isParseBigDecimal() {
    808         return ndf.isParseBigDecimal();
    809     }
    810 
    811     /**
    812      * Sets the flag that indicates whether numbers will be parsed as integers.
    813      * When this decimal format is used for parsing and this value is set to
    814      * {@code true}, then the resulting numbers will be of type
    815      * {@code java.lang.Integer}. Special cases are NaN, positive and negative
    816      * infinity, which are still returned as {@code java.lang.Double}.
    817      *
    818      *
    819      * @param value
    820      *            {@code true} that the resulting numbers of parse operations
    821      *            will be of type {@code java.lang.Integer} except for the
    822      *            special cases described above.
    823      */
    824     @Override
    825     public void setParseIntegerOnly(boolean value) {
    826         // In this implementation, NativeDecimalFormat is wrapped to
    827         // fulfill most of the format and parse feature. And this method is
    828         // delegated to the wrapped instance of NativeDecimalFormat.
    829         ndf.setParseIntegerOnly(value);
    830     }
    831 
    832     /**
    833      * Indicates whether parsing with this decimal format will only
    834      * return numbers of type {@code java.lang.Integer}.
    835      *
    836      * @return {@code true} if this {@code DecimalFormat}'s parse method only
    837      *         returns {@code java.lang.Integer}; {@code false} otherwise.
    838      */
    839     @Override
    840     public boolean isParseIntegerOnly() {
    841         return ndf.isParseIntegerOnly();
    842     }
    843 
    844     private static final Double NEGATIVE_ZERO_DOUBLE = new Double(-0.0);
    845 
    846     /**
    847      * Parses a {@code Long} or {@code Double} from the specified string
    848      * starting at the index specified by {@code position}. If the string is
    849      * successfully parsed then the index of the {@code ParsePosition} is
    850      * updated to the index following the parsed text. On error, the index is
    851      * unchanged and the error index of {@code ParsePosition} is set to the
    852      * index where the error occurred.
    853      *
    854      * @param string
    855      *            the string to parse.
    856      * @param position
    857      *            input/output parameter, specifies the start index in
    858      *            {@code string} from where to start parsing. If parsing is
    859      *            successful, it is updated with the index following the parsed
    860      *            text; on error, the index is unchanged and the error index is
    861      *            set to the index where the error occurred.
    862      * @return a {@code Long} or {@code Double} resulting from the parse or
    863      *         {@code null} if there is an error. The result will be a
    864      *         {@code Long} if the parsed number is an integer in the range of a
    865      *         long, otherwise the result is a {@code Double}. If
    866      *         {@code isParseBigDecimal} is {@code true} then it returns the
    867      *         result as a {@code BigDecimal}.
    868      */
    869     @Override
    870     public Number parse(String string, ParsePosition position) {
    871         Number number = ndf.parse(string, position);
    872         if (number == null) {
    873             return null;
    874         }
    875         if (this.isParseBigDecimal()) {
    876             if (number instanceof Long) {
    877                 return new BigDecimal(number.longValue());
    878             }
    879             if ((number instanceof Double) && !((Double) number).isInfinite()
    880                     && !((Double) number).isNaN()) {
    881 
    882                 return new BigDecimal(number.toString());
    883             }
    884             if (number instanceof BigInteger) {
    885                 return new BigDecimal(number.toString());
    886             }
    887             return number;
    888         }
    889         if ((number instanceof BigDecimal) || (number instanceof BigInteger)) {
    890             return new Double(number.doubleValue());
    891         }
    892         if (this.isParseIntegerOnly() && number.equals(NEGATIVE_ZERO_DOUBLE)) {
    893             return Long.valueOf(0);
    894         }
    895         return number;
    896 
    897     }
    898 
    899     /**
    900      * Sets the {@code DecimalFormatSymbols} used by this decimal format.
    901      *
    902      * @param value
    903      *            the {@code DecimalFormatSymbols} to set.
    904      */
    905     public void setDecimalFormatSymbols(DecimalFormatSymbols value) {
    906         if (value != null) {
    907             // The Java object is canonical, and we copy down to native code.
    908             this.symbols = (DecimalFormatSymbols) value.clone();
    909             ndf.setDecimalFormatSymbols(this.symbols);
    910         }
    911     }
    912 
    913     /**
    914      * Sets the currency used by this decimal format. The min and max fraction
    915      * digits remain the same.
    916      *
    917      * @param currency
    918      *            the currency this {@code DecimalFormat} should use.
    919      * @see DecimalFormatSymbols#setCurrency(Currency)
    920      */
    921     @Override
    922     public void setCurrency(Currency currency) {
    923         ndf.setCurrency(Currency.getInstance(currency.getCurrencyCode()));
    924         symbols.setCurrency(currency);
    925     }
    926 
    927     /**
    928      * Sets whether the decimal separator is shown when there are no fractional
    929      * digits.
    930      *
    931      * @param value
    932      *            {@code true} if the decimal separator should always be
    933      *            formatted; {@code false} otherwise.
    934      */
    935     public void setDecimalSeparatorAlwaysShown(boolean value) {
    936         ndf.setDecimalSeparatorAlwaysShown(value);
    937     }
    938 
    939     /**
    940      * Sets the number of digits grouped together by the grouping separator.
    941      * This only allows to set the primary grouping size; the secondary grouping
    942      * size can only be set with a pattern.
    943      *
    944      * @param value
    945      *            the number of digits grouped together.
    946      */
    947     public void setGroupingSize(int value) {
    948         ndf.setGroupingSize(value);
    949     }
    950 
    951     /**
    952      * Sets whether or not grouping will be used in this format. Grouping
    953      * affects both parsing and formatting.
    954      *
    955      * @param value
    956      *            {@code true} if grouping is used; {@code false} otherwise.
    957      */
    958     @Override
    959     public void setGroupingUsed(boolean value) {
    960         ndf.setGroupingUsed(value);
    961     }
    962 
    963     /**
    964      * Indicates whether grouping will be used in this format.
    965      *
    966      * @return {@code true} if grouping is used; {@code false} otherwise.
    967      */
    968     @Override
    969     public boolean isGroupingUsed() {
    970         return ndf.isGroupingUsed();
    971     }
    972 
    973     /**
    974      * Sets the maximum number of digits after the decimal point.
    975      * If the value passed is negative then it is replaced by 0.
    976      * Regardless of this setting, no more than 340 digits will be used.
    977      *
    978      * @param value the maximum number of fraction digits.
    979      */
    980     @Override
    981     public void setMaximumFractionDigits(int value) {
    982         super.setMaximumFractionDigits(value);
    983         ndf.setMaximumFractionDigits(getMaximumFractionDigits());
    984         // Changing the maximum fraction digits needs to update ICU4C's rounding configuration.
    985         setRoundingMode(roundingMode);
    986     }
    987 
    988     /**
    989      * Sets the maximum number of digits before the decimal point.
    990      * If the value passed is negative then it is replaced by 0.
    991      * Regardless of this setting, no more than 309 digits will be used.
    992      *
    993      * @param value the maximum number of integer digits.
    994      */
    995     @Override
    996     public void setMaximumIntegerDigits(int value) {
    997         super.setMaximumIntegerDigits(value);
    998         ndf.setMaximumIntegerDigits(getMaximumIntegerDigits());
    999     }
   1000 
   1001     /**
   1002      * Sets the minimum number of digits after the decimal point.
   1003      * If the value passed is negative then it is replaced by 0.
   1004      * Regardless of this setting, no more than 340 digits will be used.
   1005      *
   1006      * @param value the minimum number of fraction digits.
   1007      */
   1008     @Override
   1009     public void setMinimumFractionDigits(int value) {
   1010         super.setMinimumFractionDigits(value);
   1011         ndf.setMinimumFractionDigits(getMinimumFractionDigits());
   1012     }
   1013 
   1014     /**
   1015      * Sets the minimum number of digits before the decimal point.
   1016      * If the value passed is negative then it is replaced by 0.
   1017      * Regardless of this setting, no more than 309 digits will be used.
   1018      *
   1019      * @param value the minimum number of integer digits.
   1020      */
   1021     @Override
   1022     public void setMinimumIntegerDigits(int value) {
   1023         super.setMinimumIntegerDigits(value);
   1024         ndf.setMinimumIntegerDigits(getMinimumIntegerDigits());
   1025     }
   1026 
   1027     /**
   1028      * Sets the multiplier which is applied to the number before formatting or
   1029      * after parsing.
   1030      *
   1031      * @param value
   1032      *            the multiplier.
   1033      */
   1034     public void setMultiplier(int value) {
   1035         ndf.setMultiplier(value);
   1036     }
   1037 
   1038     /**
   1039      * Sets the prefix which is formatted or parsed before a negative number.
   1040      *
   1041      * @param value
   1042      *            the negative prefix.
   1043      */
   1044     public void setNegativePrefix(String value) {
   1045         ndf.setNegativePrefix(value);
   1046     }
   1047 
   1048     /**
   1049      * Sets the suffix which is formatted or parsed after a negative number.
   1050      *
   1051      * @param value
   1052      *            the negative suffix.
   1053      */
   1054     public void setNegativeSuffix(String value) {
   1055         ndf.setNegativeSuffix(value);
   1056     }
   1057 
   1058     /**
   1059      * Sets the prefix which is formatted or parsed before a positive number.
   1060      *
   1061      * @param value
   1062      *            the positive prefix.
   1063      */
   1064     public void setPositivePrefix(String value) {
   1065         ndf.setPositivePrefix(value);
   1066     }
   1067 
   1068     /**
   1069      * Sets the suffix which is formatted or parsed after a positive number.
   1070      *
   1071      * @param value
   1072      *            the positive suffix.
   1073      */
   1074     public void setPositiveSuffix(String value) {
   1075         ndf.setPositiveSuffix(value);
   1076     }
   1077 
   1078     /**
   1079      * Sets the behavior of the parse method. If set to {@code true} then all
   1080      * the returned objects will be of type {@code BigDecimal}.
   1081      *
   1082      * @param newValue
   1083      *            {@code true} if all the returned objects should be of type
   1084      *            {@code BigDecimal}; {@code false} otherwise.
   1085      */
   1086     public void setParseBigDecimal(boolean newValue) {
   1087         ndf.setParseBigDecimal(newValue);
   1088     }
   1089 
   1090     /**
   1091      * Returns the pattern of this decimal format using localized pattern
   1092      * characters.
   1093      *
   1094      * @return the localized pattern.
   1095      */
   1096     public String toLocalizedPattern() {
   1097         return ndf.toLocalizedPattern();
   1098     }
   1099 
   1100     /**
   1101      * Returns the pattern of this decimal format using non-localized pattern
   1102      * characters.
   1103      *
   1104      * @return the non-localized pattern.
   1105      */
   1106     public String toPattern() {
   1107         return ndf.toPattern();
   1108     }
   1109 
   1110     // the fields list to be serialized
   1111     private static final ObjectStreamField[] serialPersistentFields = {
   1112         new ObjectStreamField("positivePrefix", String.class),
   1113         new ObjectStreamField("positiveSuffix", String.class),
   1114         new ObjectStreamField("negativePrefix", String.class),
   1115         new ObjectStreamField("negativeSuffix", String.class),
   1116         new ObjectStreamField("posPrefixPattern", String.class),
   1117         new ObjectStreamField("posSuffixPattern", String.class),
   1118         new ObjectStreamField("negPrefixPattern", String.class),
   1119         new ObjectStreamField("negSuffixPattern", String.class),
   1120         new ObjectStreamField("multiplier", int.class),
   1121         new ObjectStreamField("groupingSize", byte.class),
   1122         new ObjectStreamField("groupingUsed", boolean.class),
   1123         new ObjectStreamField("decimalSeparatorAlwaysShown", boolean.class),
   1124         new ObjectStreamField("parseBigDecimal", boolean.class),
   1125         new ObjectStreamField("roundingMode", RoundingMode.class),
   1126         new ObjectStreamField("symbols", DecimalFormatSymbols.class),
   1127         new ObjectStreamField("useExponentialNotation", boolean.class),
   1128         new ObjectStreamField("minExponentDigits", byte.class),
   1129         new ObjectStreamField("maximumIntegerDigits", int.class),
   1130         new ObjectStreamField("minimumIntegerDigits", int.class),
   1131         new ObjectStreamField("maximumFractionDigits", int.class),
   1132         new ObjectStreamField("minimumFractionDigits", int.class),
   1133         new ObjectStreamField("serialVersionOnStream", int.class),
   1134     };
   1135 
   1136     /**
   1137      * Writes serialized fields following serialized forms specified by Java
   1138      * specification.
   1139      *
   1140      * @param stream
   1141      *            the output stream to write serialized bytes
   1142      * @throws IOException
   1143      *             if some I/O error occurs
   1144      * @throws ClassNotFoundException
   1145      */
   1146     private void writeObject(ObjectOutputStream stream) throws IOException, ClassNotFoundException {
   1147         ObjectOutputStream.PutField fields = stream.putFields();
   1148         fields.put("positivePrefix", ndf.getPositivePrefix());
   1149         fields.put("positiveSuffix", ndf.getPositiveSuffix());
   1150         fields.put("negativePrefix", ndf.getNegativePrefix());
   1151         fields.put("negativeSuffix", ndf.getNegativeSuffix());
   1152         fields.put("posPrefixPattern", (String) null);
   1153         fields.put("posSuffixPattern", (String) null);
   1154         fields.put("negPrefixPattern", (String) null);
   1155         fields.put("negSuffixPattern", (String) null);
   1156         fields.put("multiplier", ndf.getMultiplier());
   1157         fields.put("groupingSize", (byte) ndf.getGroupingSize());
   1158         fields.put("groupingUsed", ndf.isGroupingUsed());
   1159         fields.put("decimalSeparatorAlwaysShown", ndf.isDecimalSeparatorAlwaysShown());
   1160         fields.put("parseBigDecimal", ndf.isParseBigDecimal());
   1161         fields.put("roundingMode", roundingMode);
   1162         fields.put("symbols", symbols);
   1163         fields.put("useExponentialNotation", false);
   1164         fields.put("minExponentDigits", (byte) 0);
   1165         fields.put("maximumIntegerDigits", ndf.getMaximumIntegerDigits());
   1166         fields.put("minimumIntegerDigits", ndf.getMinimumIntegerDigits());
   1167         fields.put("maximumFractionDigits", ndf.getMaximumFractionDigits());
   1168         fields.put("minimumFractionDigits", ndf.getMinimumFractionDigits());
   1169         fields.put("serialVersionOnStream", 4);
   1170         stream.writeFields();
   1171     }
   1172 
   1173     /**
   1174      * Reads serialized fields following serialized forms specified by Java
   1175      * specification.
   1176      *
   1177      * @param stream
   1178      *            the input stream to read serialized bytes
   1179      * @throws IOException
   1180      *             if some I/O error occurs
   1181      * @throws ClassNotFoundException
   1182      *             if some class of serialized objects or fields cannot be found
   1183      */
   1184     private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
   1185         ObjectInputStream.GetField fields = stream.readFields();
   1186         this.symbols = (DecimalFormatSymbols) fields.get("symbols", null);
   1187 
   1188         initNative("");
   1189         ndf.setPositivePrefix((String) fields.get("positivePrefix", ""));
   1190         ndf.setPositiveSuffix((String) fields.get("positiveSuffix", ""));
   1191         ndf.setNegativePrefix((String) fields.get("negativePrefix", "-"));
   1192         ndf.setNegativeSuffix((String) fields.get("negativeSuffix", ""));
   1193         ndf.setMultiplier(fields.get("multiplier", 1));
   1194         ndf.setGroupingSize(fields.get("groupingSize", (byte) 3));
   1195         ndf.setGroupingUsed(fields.get("groupingUsed", true));
   1196         ndf.setDecimalSeparatorAlwaysShown(fields.get("decimalSeparatorAlwaysShown", false));
   1197 
   1198         setRoundingMode((RoundingMode) fields.get("roundingMode", RoundingMode.HALF_EVEN));
   1199 
   1200         final int maximumIntegerDigits = fields.get("maximumIntegerDigits", 309);
   1201         final int minimumIntegerDigits = fields.get("minimumIntegerDigits", 309);
   1202         final int maximumFractionDigits = fields.get("maximumFractionDigits", 340);
   1203         final int minimumFractionDigits = fields.get("minimumFractionDigits", 340);
   1204         // Tell ICU what we want, then ask it what we can have, and then
   1205         // set that in our Java object. This isn't RI-compatible, but then very little of our
   1206         // behavior in this area is, and it's not obvious how we can second-guess ICU (or tell
   1207         // it to just do exactly what we ask). We only need to do this with maximumIntegerDigits
   1208         // because ICU doesn't seem to have its own ideas about the other options.
   1209         ndf.setMaximumIntegerDigits(maximumIntegerDigits);
   1210         super.setMaximumIntegerDigits(ndf.getMaximumIntegerDigits());
   1211 
   1212         setMinimumIntegerDigits(minimumIntegerDigits);
   1213         setMinimumFractionDigits(minimumFractionDigits);
   1214         setMaximumFractionDigits(maximumFractionDigits);
   1215         setParseBigDecimal(fields.get("parseBigDecimal", false));
   1216 
   1217         if (fields.get("serialVersionOnStream", 0) < 3) {
   1218             setMaximumIntegerDigits(super.getMaximumIntegerDigits());
   1219             setMinimumIntegerDigits(super.getMinimumIntegerDigits());
   1220             setMaximumFractionDigits(super.getMaximumFractionDigits());
   1221             setMinimumFractionDigits(super.getMinimumFractionDigits());
   1222         }
   1223     }
   1224 
   1225     /**
   1226      * Returns the {@code RoundingMode} used by this {@code NumberFormat}.
   1227      * @since 1.6
   1228      */
   1229     public RoundingMode getRoundingMode() {
   1230         return roundingMode;
   1231     }
   1232 
   1233     /**
   1234      * Sets the {@code RoundingMode} used by this {@code NumberFormat}.
   1235      * @since 1.6
   1236      */
   1237     public void setRoundingMode(RoundingMode roundingMode) {
   1238         if (roundingMode == null) {
   1239             throw new NullPointerException("roundingMode == null");
   1240         }
   1241         this.roundingMode = roundingMode;
   1242         if (roundingMode != RoundingMode.UNNECESSARY) { // ICU4C doesn't support UNNECESSARY.
   1243             double roundingIncrement = 1.0 / Math.pow(10, Math.max(0, getMaximumFractionDigits()));
   1244             ndf.setRoundingMode(roundingMode, roundingIncrement);
   1245         }
   1246     }
   1247 }
   1248