DecimalFormat.java revision 46cb23aaaba1b0553d02d32713abad97bd4b0428
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
18package java.text;
19
20import com.ibm.icu4jni.text.NativeDecimalFormat;
21import com.ibm.icu4jni.util.LocaleData;
22import java.io.IOException;
23import java.io.ObjectInputStream;
24import java.io.ObjectOutputStream;
25import java.io.ObjectStreamField;
26import java.math.BigDecimal;
27import java.math.BigInteger;
28import java.math.RoundingMode;
29import java.util.Currency;
30import java.util.Locale;
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 &#92;u2030})</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 &#164;} ({@code &#92;u00A4})</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 &#92;uFFFD}. 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 &#92;u221E},
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 */
498public class DecimalFormat extends NumberFormat {
499
500    private static final long serialVersionUID = 864413376551465018L;
501
502    private transient DecimalFormatSymbols symbols;
503
504    private transient NativeDecimalFormat dform;
505    private final Object finalizerGuardian = new Object() {
506        @Override protected void finalize() throws Throwable {
507            dform.close();
508        }
509    };
510
511    private transient RoundingMode roundingMode = RoundingMode.HALF_EVEN;
512
513    /**
514     * Constructs a new {@code DecimalFormat} for formatting and parsing numbers
515     * for the user's default locale.
516     * See "<a href="../util/Locale.html#default_locale">Be wary of the default locale</a>".
517     */
518    public DecimalFormat() {
519        Locale locale = Locale.getDefault();
520        this.symbols = new DecimalFormatSymbols(locale);
521        initNative(LocaleData.get(locale).numberPattern);
522    }
523
524    /**
525     * Constructs a new {@code DecimalFormat} using the specified non-localized
526     * pattern and the {@code DecimalFormatSymbols} for the user's default Locale.
527     * See "<a href="../util/Locale.html#default_locale">Be wary of the default locale</a>".
528     * @param pattern
529     *            the non-localized pattern.
530     * @throws IllegalArgumentException
531     *            if the pattern cannot be parsed.
532     */
533    public DecimalFormat(String pattern) {
534        this(pattern, Locale.getDefault());
535    }
536
537    /**
538     * Constructs a new {@code DecimalFormat} using the specified non-localized
539     * pattern and {@code DecimalFormatSymbols}.
540     *
541     * @param pattern
542     *            the non-localized pattern.
543     * @param value
544     *            the DecimalFormatSymbols.
545     * @throws IllegalArgumentException
546     *            if the pattern cannot be parsed.
547     */
548    public DecimalFormat(String pattern, DecimalFormatSymbols value) {
549        this.symbols = (DecimalFormatSymbols) value.clone();
550        initNative(pattern);
551    }
552
553    // Used by NumberFormat.getInstance because cloning DecimalFormatSymbols is slow.
554    DecimalFormat(String pattern, Locale locale) {
555        this.symbols = new DecimalFormatSymbols(locale);
556        initNative(pattern);
557    }
558
559    private void initNative(String pattern) {
560        try {
561            this.dform = new NativeDecimalFormat(pattern, symbols);
562        } catch (IllegalArgumentException ex) {
563            throw new IllegalArgumentException(pattern);
564        }
565        super.setMaximumFractionDigits(dform.getMaximumFractionDigits());
566        super.setMaximumIntegerDigits(dform.getMaximumIntegerDigits());
567        super.setMinimumFractionDigits(dform.getMinimumFractionDigits());
568        super.setMinimumIntegerDigits(dform.getMinimumIntegerDigits());
569    }
570
571    /**
572     * Changes the pattern of this decimal format to the specified pattern which
573     * uses localized pattern characters.
574     *
575     * @param pattern
576     *            the localized pattern.
577     * @throws IllegalArgumentException
578     *            if the pattern cannot be parsed.
579     */
580    public void applyLocalizedPattern(String pattern) {
581        dform.applyLocalizedPattern(pattern);
582    }
583
584    /**
585     * Changes the pattern of this decimal format to the specified pattern which
586     * uses non-localized pattern characters.
587     *
588     * @param pattern
589     *            the non-localized pattern.
590     * @throws IllegalArgumentException
591     *            if the pattern cannot be parsed.
592     */
593    public void applyPattern(String pattern) {
594        dform.applyPattern(pattern);
595    }
596
597    /**
598     * Returns a new instance of {@code DecimalFormat} with the same pattern and
599     * properties as this decimal format.
600     *
601     * @return a shallow copy of this decimal format.
602     * @see java.lang.Cloneable
603     */
604    @Override
605    public Object clone() {
606        DecimalFormat clone = (DecimalFormat) super.clone();
607        clone.dform = (NativeDecimalFormat) dform.clone();
608        clone.symbols = (DecimalFormatSymbols) symbols.clone();
609        return clone;
610    }
611
612    /**
613     * Compares the specified object to this decimal format and indicates if
614     * they are equal. In order to be equal, {@code object} must be an instance
615     * of {@code DecimalFormat} with the same pattern and properties.
616     *
617     * @param object
618     *            the object to compare with this object.
619     * @return {@code true} if the specified object is equal to this decimal
620     *         format; {@code false} otherwise.
621     * @see #hashCode
622     */
623    @Override
624    public boolean equals(Object object) {
625        if (this == object) {
626            return true;
627        }
628        if (!(object instanceof DecimalFormat)) {
629            return false;
630        }
631        DecimalFormat other = (DecimalFormat) object;
632        return (this.dform == null ? other.dform == null : this.dform.equals(other.dform)) &&
633                getDecimalFormatSymbols().equals(other.getDecimalFormatSymbols());
634    }
635
636    /**
637     * Formats the specified object using the rules of this decimal format and
638     * returns an {@code AttributedCharacterIterator} with the formatted number
639     * and attributes.
640     *
641     * @param object
642     *            the object to format.
643     * @return an AttributedCharacterIterator with the formatted number and
644     *         attributes.
645     * @throws IllegalArgumentException
646     *             if {@code object} cannot be formatted by this format.
647     * @throws NullPointerException
648     *             if {@code object} is {@code null}.
649     */
650    @Override
651    public AttributedCharacterIterator formatToCharacterIterator(Object object) {
652        if (object == null) {
653            throw new NullPointerException();
654        }
655        return dform.formatToCharacterIterator(object);
656    }
657
658    private void checkBufferAndFieldPosition(StringBuffer buffer, FieldPosition position) {
659        if (buffer == null) {
660            throw new NullPointerException("buffer == null");
661        }
662        if (position == null) {
663            throw new NullPointerException("position == null");
664        }
665    }
666
667    @Override
668    public StringBuffer format(double value, StringBuffer buffer, FieldPosition position) {
669        checkBufferAndFieldPosition(buffer, position);
670        // All float/double/Float/Double formatting ends up here...
671        if (roundingMode == RoundingMode.UNNECESSARY) {
672            // ICU4C doesn't support this rounding mode, so we have to fake it.
673            try {
674                setRoundingMode(RoundingMode.UP);
675                String upResult = format(value, new StringBuffer(), new FieldPosition(0)).toString();
676                setRoundingMode(RoundingMode.DOWN);
677                String downResult = format(value, new StringBuffer(), new FieldPosition(0)).toString();
678                if (!upResult.equals(downResult)) {
679                    throw new ArithmeticException("rounding mode UNNECESSARY but rounding required");
680                }
681            } finally {
682                setRoundingMode(RoundingMode.UNNECESSARY);
683            }
684        }
685        buffer.append(dform.formatDouble(value, position));
686        return buffer;
687    }
688
689    @Override
690    public StringBuffer format(long value, StringBuffer buffer, FieldPosition position) {
691        checkBufferAndFieldPosition(buffer, position);
692        buffer.append(dform.formatLong(value, position));
693        return buffer;
694    }
695
696    @Override
697    public final StringBuffer format(Object number, StringBuffer buffer, FieldPosition position) {
698        checkBufferAndFieldPosition(buffer, position);
699        if (number instanceof BigInteger) {
700            BigInteger bigInteger = (BigInteger) number;
701            char[] chars = (bigInteger.bitLength() < 64)
702                    ? dform.formatLong(bigInteger.longValue(), position)
703                    : dform.formatBigInteger(bigInteger, position);
704            buffer.append(chars);
705            return buffer;
706        } else if (number instanceof BigDecimal) {
707            buffer.append(dform.formatBigDecimal((BigDecimal) number, position));
708            return buffer;
709        }
710        return super.format(number, buffer, position);
711    }
712
713    /**
714     * Returns the {@code DecimalFormatSymbols} used by this decimal format.
715     *
716     * @return a copy of the {@code DecimalFormatSymbols} used by this decimal
717     *         format.
718     */
719    public DecimalFormatSymbols getDecimalFormatSymbols() {
720        return (DecimalFormatSymbols) symbols.clone();
721    }
722
723    /**
724     * Returns the currency used by this decimal format.
725     *
726     * @return the currency used by this decimal format.
727     * @see DecimalFormatSymbols#getCurrency()
728     */
729    @Override
730    public Currency getCurrency() {
731        return symbols.getCurrency();
732    }
733
734    /**
735     * Returns the number of digits grouped together by the grouping separator.
736     * This only allows to get the primary grouping size. There is no API to get
737     * the secondary grouping size.
738     *
739     * @return the number of digits grouped together.
740     */
741    public int getGroupingSize() {
742        return dform.getGroupingSize();
743    }
744
745    /**
746     * Returns the multiplier which is applied to the number before formatting
747     * or after parsing.
748     *
749     * @return the multiplier.
750     */
751    public int getMultiplier() {
752        return dform.getMultiplier();
753    }
754
755    /**
756     * Returns the prefix which is formatted or parsed before a negative number.
757     *
758     * @return the negative prefix.
759     */
760    public String getNegativePrefix() {
761        return dform.getNegativePrefix();
762    }
763
764    /**
765     * Returns the suffix which is formatted or parsed after a negative number.
766     *
767     * @return the negative suffix.
768     */
769    public String getNegativeSuffix() {
770        return dform.getNegativeSuffix();
771    }
772
773    /**
774     * Returns the prefix which is formatted or parsed before a positive number.
775     *
776     * @return the positive prefix.
777     */
778    public String getPositivePrefix() {
779        return dform.getPositivePrefix();
780    }
781
782    /**
783     * Returns the suffix which is formatted or parsed after a positive number.
784     *
785     * @return the positive suffix.
786     */
787    public String getPositiveSuffix() {
788        return dform.getPositiveSuffix();
789    }
790
791    @Override
792    public int hashCode() {
793        return dform.hashCode();
794    }
795
796    /**
797     * Indicates whether the decimal separator is shown when there are no
798     * fractional digits.
799     *
800     * @return {@code true} if the decimal separator should always be formatted;
801     *         {@code false} otherwise.
802     */
803    public boolean isDecimalSeparatorAlwaysShown() {
804        return dform.isDecimalSeparatorAlwaysShown();
805    }
806
807    /**
808     * This value indicates whether the return object of the parse operation is
809     * of type {@code BigDecimal}. This value defaults to {@code false}.
810     *
811     * @return {@code true} if parse always returns {@code BigDecimals},
812     *         {@code false} if the type of the result is {@code Long} or
813     *         {@code Double}.
814     */
815    public boolean isParseBigDecimal() {
816        return dform.isParseBigDecimal();
817    }
818
819    /**
820     * Sets the flag that indicates whether numbers will be parsed as integers.
821     * When this decimal format is used for parsing and this value is set to
822     * {@code true}, then the resulting numbers will be of type
823     * {@code java.lang.Integer}. Special cases are NaN, positive and negative
824     * infinity, which are still returned as {@code java.lang.Double}.
825     *
826     *
827     * @param value
828     *            {@code true} that the resulting numbers of parse operations
829     *            will be of type {@code java.lang.Integer} except for the
830     *            special cases described above.
831     */
832    @Override
833    public void setParseIntegerOnly(boolean value) {
834        // In this implementation, NativeDecimalFormat is wrapped to
835        // fulfill most of the format and parse feature. And this method is
836        // delegated to the wrapped instance of NativeDecimalFormat.
837        dform.setParseIntegerOnly(value);
838    }
839
840    /**
841     * Indicates whether parsing with this decimal format will only
842     * return numbers of type {@code java.lang.Integer}.
843     *
844     * @return {@code true} if this {@code DecimalFormat}'s parse method only
845     *         returns {@code java.lang.Integer}; {@code false} otherwise.
846     */
847    @Override
848    public boolean isParseIntegerOnly() {
849        return dform.isParseIntegerOnly();
850    }
851
852    private static final Double NEGATIVE_ZERO_DOUBLE = new Double(-0.0);
853
854    /**
855     * Parses a {@code Long} or {@code Double} from the specified string
856     * starting at the index specified by {@code position}. If the string is
857     * successfully parsed then the index of the {@code ParsePosition} is
858     * updated to the index following the parsed text. On error, the index is
859     * unchanged and the error index of {@code ParsePosition} is set to the
860     * index where the error occurred.
861     *
862     * @param string
863     *            the string to parse.
864     * @param position
865     *            input/output parameter, specifies the start index in
866     *            {@code string} from where to start parsing. If parsing is
867     *            successful, it is updated with the index following the parsed
868     *            text; on error, the index is unchanged and the error index is
869     *            set to the index where the error occurred.
870     * @return a {@code Long} or {@code Double} resulting from the parse or
871     *         {@code null} if there is an error. The result will be a
872     *         {@code Long} if the parsed number is an integer in the range of a
873     *         long, otherwise the result is a {@code Double}. If
874     *         {@code isParseBigDecimal} is {@code true} then it returns the
875     *         result as a {@code BigDecimal}.
876     */
877    @Override
878    public Number parse(String string, ParsePosition position) {
879        Number number = dform.parse(string, position);
880        if (null == number) {
881            return null;
882        }
883        // BEGIN android-removed
884        // if (this.isParseBigDecimal()) {
885        //     if (number instanceof Long) {
886        //         return new BigDecimal(number.longValue());
887        //     }
888        //     if ((number instanceof Double) && !((Double) number).isInfinite()
889        //             && !((Double) number).isNaN()) {
890        //
891        //         return new BigDecimal(number.doubleValue());
892        //     }
893        //     if (number instanceof BigInteger) {
894        //         return new BigDecimal(number.doubleValue());
895        //     }
896        //     if (number instanceof com.ibm.icu.math.BigDecimal) {
897        //         return new BigDecimal(number.toString());
898        //     }
899        //     return number;
900        // }
901        // if ((number instanceof com.ibm.icu.math.BigDecimal)
902        //         || (number instanceof BigInteger)) {
903        //     return new Double(number.doubleValue());
904        // }
905        // END android-removed
906        // BEGIN android-added
907        if (this.isParseBigDecimal()) {
908            if (number instanceof Long) {
909                return new BigDecimal(number.longValue());
910            }
911            if ((number instanceof Double) && !((Double) number).isInfinite()
912                    && !((Double) number).isNaN()) {
913
914                return new BigDecimal(number.toString());
915            }
916            if (number instanceof BigInteger) {
917                return new BigDecimal(number.toString());
918            }
919            return number;
920        }
921        if ((number instanceof BigDecimal) || (number instanceof BigInteger)) {
922            return new Double(number.doubleValue());
923        }
924        // END android-added
925
926        if (this.isParseIntegerOnly() && number.equals(NEGATIVE_ZERO_DOUBLE)) {
927            return Long.valueOf(0); // android-changed
928        }
929        return number;
930
931    }
932
933    /**
934     * Sets the {@code DecimalFormatSymbols} used by this decimal format.
935     *
936     * @param value
937     *            the {@code DecimalFormatSymbols} to set.
938     */
939    public void setDecimalFormatSymbols(DecimalFormatSymbols value) {
940        if (value != null) {
941            // BEGIN android-changed: the Java object is canonical, and we copy down to native code.
942            this.symbols = (DecimalFormatSymbols) value.clone();
943            dform.setDecimalFormatSymbols(this.symbols);
944            // END android-changed
945        }
946    }
947
948    /**
949     * Sets the currency used by this decimal format. The min and max fraction
950     * digits remain the same.
951     *
952     * @param currency
953     *            the currency this {@code DecimalFormat} should use.
954     * @see DecimalFormatSymbols#setCurrency(Currency)
955     */
956    @Override
957    public void setCurrency(Currency currency) {
958        // BEGIN android-changed
959        dform.setCurrency(Currency.getInstance(currency.getCurrencyCode()));
960        // END android-changed
961        symbols.setCurrency(currency);
962    }
963
964    /**
965     * Sets whether the decimal separator is shown when there are no fractional
966     * digits.
967     *
968     * @param value
969     *            {@code true} if the decimal separator should always be
970     *            formatted; {@code false} otherwise.
971     */
972    public void setDecimalSeparatorAlwaysShown(boolean value) {
973        dform.setDecimalSeparatorAlwaysShown(value);
974    }
975
976    /**
977     * Sets the number of digits grouped together by the grouping separator.
978     * This only allows to set the primary grouping size; the secondary grouping
979     * size can only be set with a pattern.
980     *
981     * @param value
982     *            the number of digits grouped together.
983     */
984    public void setGroupingSize(int value) {
985        dform.setGroupingSize(value);
986    }
987
988    /**
989     * Sets whether or not grouping will be used in this format. Grouping
990     * affects both parsing and formatting.
991     *
992     * @param value
993     *            {@code true} if grouping is used; {@code false} otherwise.
994     */
995    @Override
996    public void setGroupingUsed(boolean value) {
997        dform.setGroupingUsed(value);
998    }
999
1000    /**
1001     * Indicates whether grouping will be used in this format.
1002     *
1003     * @return {@code true} if grouping is used; {@code false} otherwise.
1004     */
1005    @Override
1006    public boolean isGroupingUsed() {
1007        return dform.isGroupingUsed();
1008    }
1009
1010    /**
1011     * Sets the maximum number of digits after the decimal point.
1012     * If the value passed is negative then it is replaced by 0.
1013     * Regardless of this setting, no more than 340 digits will be used.
1014     *
1015     * @param value the maximum number of fraction digits.
1016     */
1017    @Override
1018    public void setMaximumFractionDigits(int value) {
1019        super.setMaximumFractionDigits(value);
1020        dform.setMaximumFractionDigits(getMaximumFractionDigits());
1021        // Changing the maximum fraction digits needs to update ICU4C's rounding configuration.
1022        setRoundingMode(roundingMode);
1023    }
1024
1025    /**
1026     * Sets the maximum number of digits before the decimal point.
1027     * If the value passed is negative then it is replaced by 0.
1028     * Regardless of this setting, no more than 309 digits will be used.
1029     *
1030     * @param value the maximum number of integer digits.
1031     */
1032    @Override
1033    public void setMaximumIntegerDigits(int value) {
1034        super.setMaximumIntegerDigits(value);
1035        dform.setMaximumIntegerDigits(getMaximumIntegerDigits());
1036    }
1037
1038    /**
1039     * Sets the minimum number of digits after the decimal point.
1040     * If the value passed is negative then it is replaced by 0.
1041     * Regardless of this setting, no more than 340 digits will be used.
1042     *
1043     * @param value the minimum number of fraction digits.
1044     */
1045    @Override
1046    public void setMinimumFractionDigits(int value) {
1047        super.setMinimumFractionDigits(value);
1048        dform.setMinimumFractionDigits(getMinimumFractionDigits());
1049    }
1050
1051    /**
1052     * Sets the minimum number of digits before the decimal point.
1053     * If the value passed is negative then it is replaced by 0.
1054     * Regardless of this setting, no more than 309 digits will be used.
1055     *
1056     * @param value the minimum number of integer digits.
1057     */
1058    @Override
1059    public void setMinimumIntegerDigits(int value) {
1060        super.setMinimumIntegerDigits(value);
1061        dform.setMinimumIntegerDigits(getMinimumIntegerDigits());
1062    }
1063
1064    /**
1065     * Sets the multiplier which is applied to the number before formatting or
1066     * after parsing.
1067     *
1068     * @param value
1069     *            the multiplier.
1070     */
1071    public void setMultiplier(int value) {
1072        dform.setMultiplier(value);
1073    }
1074
1075    /**
1076     * Sets the prefix which is formatted or parsed before a negative number.
1077     *
1078     * @param value
1079     *            the negative prefix.
1080     */
1081    public void setNegativePrefix(String value) {
1082        dform.setNegativePrefix(value);
1083    }
1084
1085    /**
1086     * Sets the suffix which is formatted or parsed after a negative number.
1087     *
1088     * @param value
1089     *            the negative suffix.
1090     */
1091    public void setNegativeSuffix(String value) {
1092        dform.setNegativeSuffix(value);
1093    }
1094
1095    /**
1096     * Sets the prefix which is formatted or parsed before a positive number.
1097     *
1098     * @param value
1099     *            the positive prefix.
1100     */
1101    public void setPositivePrefix(String value) {
1102        dform.setPositivePrefix(value);
1103    }
1104
1105    /**
1106     * Sets the suffix which is formatted or parsed after a positive number.
1107     *
1108     * @param value
1109     *            the positive suffix.
1110     */
1111    public void setPositiveSuffix(String value) {
1112        dform.setPositiveSuffix(value);
1113    }
1114
1115    /**
1116     * Sets the behaviour of the parse method. If set to {@code true} then all
1117     * the returned objects will be of type {@code BigDecimal}.
1118     *
1119     * @param newValue
1120     *            {@code true} if all the returned objects should be of type
1121     *            {@code BigDecimal}; {@code false} otherwise.
1122     */
1123    public void setParseBigDecimal(boolean newValue) {
1124        dform.setParseBigDecimal(newValue);
1125    }
1126
1127    /**
1128     * Returns the pattern of this decimal format using localized pattern
1129     * characters.
1130     *
1131     * @return the localized pattern.
1132     */
1133    public String toLocalizedPattern() {
1134        return dform.toLocalizedPattern();
1135    }
1136
1137    /**
1138     * Returns the pattern of this decimal format using non-localized pattern
1139     * characters.
1140     *
1141     * @return the non-localized pattern.
1142     */
1143    public String toPattern() {
1144        return dform.toPattern();
1145    }
1146
1147    // the fields list to be serialized
1148    private static final ObjectStreamField[] serialPersistentFields = {
1149            new ObjectStreamField("positivePrefix", String.class),
1150            new ObjectStreamField("positiveSuffix", String.class),
1151            new ObjectStreamField("negativePrefix", String.class),
1152            new ObjectStreamField("negativeSuffix", String.class),
1153            new ObjectStreamField("posPrefixPattern", String.class),
1154            new ObjectStreamField("posSuffixPattern", String.class),
1155            new ObjectStreamField("negPrefixPattern", String.class),
1156            new ObjectStreamField("negSuffixPattern", String.class),
1157            new ObjectStreamField("multiplier", int.class),
1158            new ObjectStreamField("groupingSize", byte.class),
1159            new ObjectStreamField("groupingUsed", boolean.class),
1160            new ObjectStreamField("decimalSeparatorAlwaysShown", boolean.class),
1161            new ObjectStreamField("parseBigDecimal", boolean.class),
1162            new ObjectStreamField("roundingMode", RoundingMode.class),
1163            new ObjectStreamField("symbols", DecimalFormatSymbols.class),
1164            new ObjectStreamField("useExponentialNotation", boolean.class),
1165            new ObjectStreamField("minExponentDigits", byte.class),
1166            new ObjectStreamField("maximumIntegerDigits", int.class),
1167            new ObjectStreamField("minimumIntegerDigits", int.class),
1168            new ObjectStreamField("maximumFractionDigits", int.class),
1169            new ObjectStreamField("minimumFractionDigits", int.class),
1170            new ObjectStreamField("serialVersionOnStream", int.class), };
1171
1172    /**
1173     * Writes serialized fields following serialized forms specified by Java
1174     * specification.
1175     *
1176     * @param stream
1177     *            the output stream to write serialized bytes
1178     * @throws IOException
1179     *             if some I/O error occurs
1180     * @throws ClassNotFoundException
1181     */
1182    @SuppressWarnings("nls")
1183    private void writeObject(ObjectOutputStream stream) throws IOException,
1184            ClassNotFoundException {
1185        ObjectOutputStream.PutField fields = stream.putFields();
1186        fields.put("positivePrefix", dform.getPositivePrefix());
1187        fields.put("positiveSuffix", dform.getPositiveSuffix());
1188        fields.put("negativePrefix", dform.getNegativePrefix());
1189        fields.put("negativeSuffix", dform.getNegativeSuffix());
1190        fields.put("posPrefixPattern", (String) null);
1191        fields.put("posSuffixPattern", (String) null);
1192        fields.put("negPrefixPattern", (String) null);
1193        fields.put("negSuffixPattern", (String) null);
1194        fields.put("multiplier", dform.getMultiplier());
1195        fields.put("groupingSize", (byte) dform.getGroupingSize());
1196        // BEGIN android-added
1197        fields.put("groupingUsed", dform.isGroupingUsed());
1198        // END android-added
1199        fields.put("decimalSeparatorAlwaysShown", dform
1200                .isDecimalSeparatorAlwaysShown());
1201        fields.put("parseBigDecimal", dform.isParseBigDecimal());
1202        fields.put("roundingMode", roundingMode);
1203        fields.put("symbols", symbols);
1204        fields.put("useExponentialNotation", false);
1205        fields.put("minExponentDigits", (byte) 0);
1206        fields.put("maximumIntegerDigits", dform.getMaximumIntegerDigits());
1207        fields.put("minimumIntegerDigits", dform.getMinimumIntegerDigits());
1208        fields.put("maximumFractionDigits", dform.getMaximumFractionDigits());
1209        fields.put("minimumFractionDigits", dform.getMinimumFractionDigits());
1210        fields.put("serialVersionOnStream", 4);
1211        stream.writeFields();
1212    }
1213
1214    /**
1215     * Reads serialized fields following serialized forms specified by Java
1216     * specification.
1217     *
1218     * @param stream
1219     *            the input stream to read serialized bytes
1220     * @throws IOException
1221     *             if some I/O error occurs
1222     * @throws ClassNotFoundException
1223     *             if some class of serialized objects or fields cannot be found
1224     */
1225    @SuppressWarnings("nls")
1226    private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
1227        // BEGIN android-changed
1228        ObjectInputStream.GetField fields = stream.readFields();
1229        this.symbols = (DecimalFormatSymbols) fields.get("symbols", null);
1230
1231        initNative("");
1232        dform.setPositivePrefix((String) fields.get("positivePrefix", ""));
1233        dform.setPositiveSuffix((String) fields.get("positiveSuffix", ""));
1234        dform.setNegativePrefix((String) fields.get("negativePrefix", "-"));
1235        dform.setNegativeSuffix((String) fields.get("negativeSuffix", ""));
1236        dform.setMultiplier(fields.get("multiplier", 1));
1237        dform.setGroupingSize(fields.get("groupingSize", (byte) 3));
1238        dform.setGroupingUsed(fields.get("groupingUsed", true));
1239        dform.setDecimalSeparatorAlwaysShown(fields.get("decimalSeparatorAlwaysShown", false));
1240
1241        setRoundingMode((RoundingMode) fields.get("roundingMode", RoundingMode.HALF_EVEN));
1242
1243        final int maximumIntegerDigits = fields.get("maximumIntegerDigits", 309);
1244        final int minimumIntegerDigits = fields.get("minimumIntegerDigits", 309);
1245        final int maximumFractionDigits = fields.get("maximumFractionDigits", 340);
1246        final int minimumFractionDigits = fields.get("minimumFractionDigits", 340);
1247        // BEGIN android-changed: tell ICU what we want, then ask it what we can have, and then
1248        // set that in our Java object. This isn't RI-compatible, but then very little of our
1249        // behavior in this area is, and it's not obvious how we can second-guess ICU (or tell
1250        // it to just do exactly what we ask). We only need to do this with maximumIntegerDigits
1251        // because ICU doesn't seem to have its own ideas about the other options.
1252        dform.setMaximumIntegerDigits(maximumIntegerDigits);
1253        super.setMaximumIntegerDigits(dform.getMaximumIntegerDigits());
1254
1255        setMinimumIntegerDigits(minimumIntegerDigits);
1256        setMinimumFractionDigits(minimumFractionDigits);
1257        setMaximumFractionDigits(maximumFractionDigits);
1258        setParseBigDecimal(fields.get("parseBigDecimal", false));
1259
1260        if (fields.get("serialVersionOnStream", 0) < 3) {
1261            setMaximumIntegerDigits(super.getMaximumIntegerDigits());
1262            setMinimumIntegerDigits(super.getMinimumIntegerDigits());
1263            setMaximumFractionDigits(super.getMaximumFractionDigits());
1264            setMinimumFractionDigits(super.getMinimumFractionDigits());
1265        }
1266        // END android-changed
1267    }
1268
1269    /**
1270     * Returns the {@code RoundingMode} used by this {@code NumberFormat}.
1271     * @since 1.6
1272     */
1273    public RoundingMode getRoundingMode() {
1274        return roundingMode;
1275    }
1276
1277    /**
1278     * Sets the {@code RoundingMode} used by this {@code NumberFormat}.
1279     * @since 1.6
1280     */
1281    public void setRoundingMode(RoundingMode roundingMode) {
1282        if (roundingMode == null) {
1283            throw new NullPointerException();
1284        }
1285        this.roundingMode = roundingMode;
1286        if (roundingMode != RoundingMode.UNNECESSARY) { // ICU4C doesn't support UNNECESSARY.
1287            double roundingIncrement = 1.0 / Math.pow(10, Math.max(0, getMaximumFractionDigits()));
1288            dform.setRoundingMode(roundingMode, roundingIncrement);
1289        }
1290    }
1291}
1292