1/*
2 * Copyright (C) 2014 The Android Open Source Project
3 * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5 *
6 * This code is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License version 2 only, as
8 * published by the Free Software Foundation.  Oracle designates this
9 * particular file as subject to the "Classpath" exception as provided
10 * by Oracle in the LICENSE file that accompanied this code.
11 *
12 * This code is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 * version 2 for more details (a copy is included in the LICENSE file that
16 * accompanied this code).
17 *
18 * You should have received a copy of the GNU General Public License version
19 * 2 along with this work; if not, write to the Free Software Foundation,
20 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21 *
22 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
23 * or visit www.oracle.com if you need additional information or have any
24 * questions.
25 */
26
27/*
28 * (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
29 * (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved
30 *
31 *   The original version of this source code and documentation is copyrighted
32 * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These
33 * materials are provided under terms of a License Agreement between Taligent
34 * and Sun. This technology is protected by multiple US and International
35 * patents. This notice and attribution to Taligent may not be removed.
36 *   Taligent is a registered trademark of Taligent, Inc.
37 *
38 */
39
40package java.text;
41
42import java.io.InvalidObjectException;
43import java.io.IOException;
44import java.io.ObjectInputStream;
45import java.io.ObjectOutputStream;
46import java.math.BigInteger;
47import java.math.RoundingMode;
48import java.util.Currency;
49import java.util.HashMap;
50import java.util.Hashtable;
51import java.util.Locale;
52import java.util.Map;
53import java.util.concurrent.atomic.AtomicInteger;
54import java.util.concurrent.atomic.AtomicLong;
55import libcore.icu.ICU;
56import libcore.icu.LocaleData;
57
58/**
59 * <code>NumberFormat</code> is the abstract base class for all number
60 * formats. This class provides the interface for formatting and parsing
61 * numbers. <code>NumberFormat</code> also provides methods for determining
62 * which locales have number formats, and what their names are.
63 *
64 * <p>
65 * <code>NumberFormat</code> helps you to format and parse numbers for any locale.
66 * Your code can be completely independent of the locale conventions for
67 * decimal points, thousands-separators, or even the particular decimal
68 * digits used, or whether the number format is even decimal.
69 *
70 * <p>
71 * To format a number for the current Locale, use one of the factory
72 * class methods:
73 * <blockquote>
74 * <pre>{@code
75 * myString = NumberFormat.getInstance().format(myNumber);
76 * }</pre>
77 * </blockquote>
78 * If you are formatting multiple numbers, it is
79 * more efficient to get the format and use it multiple times so that
80 * the system doesn't have to fetch the information about the local
81 * language and country conventions multiple times.
82 * <blockquote>
83 * <pre>{@code
84 * NumberFormat nf = NumberFormat.getInstance();
85 * for (int i = 0; i < myNumber.length; ++i) {
86 *     output.println(nf.format(myNumber[i]) + "; ");
87 * }
88 * }</pre>
89 * </blockquote>
90 * To format a number for a different Locale, specify it in the
91 * call to <code>getInstance</code>.
92 * <blockquote>
93 * <pre>{@code
94 * NumberFormat nf = NumberFormat.getInstance(Locale.FRENCH);
95 * }</pre>
96 * </blockquote>
97 * You can also use a <code>NumberFormat</code> to parse numbers:
98 * <blockquote>
99 * <pre>{@code
100 * myNumber = nf.parse(myString);
101 * }</pre>
102 * </blockquote>
103 * Use <code>getInstance</code> or <code>getNumberInstance</code> to get the
104 * normal number format. Use <code>getIntegerInstance</code> to get an
105 * integer number format. Use <code>getCurrencyInstance</code> to get the
106 * currency number format. And use <code>getPercentInstance</code> to get a
107 * format for displaying percentages. With this format, a fraction like
108 * 0.53 is displayed as 53%.
109 *
110 * <p>
111 * You can also control the display of numbers with such methods as
112 * <code>setMinimumFractionDigits</code>.
113 * If you want even more control over the format or parsing,
114 * or want to give your users more control,
115 * you can try casting the <code>NumberFormat</code> you get from the factory methods
116 * to a <code>DecimalFormat</code>. This will work for the vast majority
117 * of locales; just remember to put it in a <code>try</code> block in case you
118 * encounter an unusual one.
119 *
120 * <p>
121 * NumberFormat and DecimalFormat are designed such that some controls
122 * work for formatting and others work for parsing.  The following is
123 * the detailed description for each these control methods,
124 * <p>
125 * setParseIntegerOnly : only affects parsing, e.g.
126 * if true,  "3456.78" &rarr; 3456 (and leaves the parse position just after index 6)
127 * if false, "3456.78" &rarr; 3456.78 (and leaves the parse position just after index 8)
128 * This is independent of formatting.  If you want to not show a decimal point
129 * where there might be no digits after the decimal point, use
130 * setDecimalSeparatorAlwaysShown.
131 * <p>
132 * setDecimalSeparatorAlwaysShown : only affects formatting, and only where
133 * there might be no digits after the decimal point, such as with a pattern
134 * like "#,##0.##", e.g.,
135 * if true,  3456.00 &rarr; "3,456."
136 * if false, 3456.00 &rarr; "3456"
137 * This is independent of parsing.  If you want parsing to stop at the decimal
138 * point, use setParseIntegerOnly.
139 *
140 * <p>
141 * You can also use forms of the <code>parse</code> and <code>format</code>
142 * methods with <code>ParsePosition</code> and <code>FieldPosition</code> to
143 * allow you to:
144 * <ul>
145 * <li> progressively parse through pieces of a string
146 * <li> align the decimal point and other areas
147 * </ul>
148 * For example, you can align numbers in two ways:
149 * <ol>
150 * <li> If you are using a monospaced font with spacing for alignment,
151 *      you can pass the <code>FieldPosition</code> in your format call, with
152 *      <code>field</code> = <code>INTEGER_FIELD</code>. On output,
153 *      <code>getEndIndex</code> will be set to the offset between the
154 *      last character of the integer and the decimal. Add
155 *      (desiredSpaceCount - getEndIndex) spaces at the front of the string.
156 *
157 * <li> If you are using proportional fonts,
158 *      instead of padding with spaces, measure the width
159 *      of the string in pixels from the start to <code>getEndIndex</code>.
160 *      Then move the pen by
161 *      (desiredPixelWidth - widthToAlignmentPoint) before drawing the text.
162 *      It also works where there is no decimal, but possibly additional
163 *      characters at the end, e.g., with parentheses in negative
164 *      numbers: "(12)" for -12.
165 * </ol>
166 *
167 * <h3><a name="synchronization">Synchronization</a></h3>
168 *
169 * <p>
170 * Number formats are generally not synchronized.
171 * It is recommended to create separate format instances for each thread.
172 * If multiple threads access a format concurrently, it must be synchronized
173 * externally.
174 *
175 * @see          DecimalFormat
176 * @see          ChoiceFormat
177 * @author       Mark Davis
178 * @author       Helena Shih
179 */
180public abstract class NumberFormat extends Format  {
181
182    /**
183     * Field constant used to construct a FieldPosition object. Signifies that
184     * the position of the integer part of a formatted number should be returned.
185     * @see java.text.FieldPosition
186     */
187    public static final int INTEGER_FIELD = 0;
188
189    /**
190     * Field constant used to construct a FieldPosition object. Signifies that
191     * the position of the fraction part of a formatted number should be returned.
192     * @see java.text.FieldPosition
193     */
194    public static final int FRACTION_FIELD = 1;
195
196    /**
197     * Sole constructor.  (For invocation by subclass constructors, typically
198     * implicit.)
199     */
200    protected NumberFormat() {
201    }
202
203    /**
204     * Formats a number and appends the resulting text to the given string
205     * buffer.
206     * The number can be of any subclass of {@link java.lang.Number}.
207     * <p>
208     * This implementation extracts the number's value using
209     * {@link java.lang.Number#longValue()} for all integral type values that
210     * can be converted to <code>long</code> without loss of information,
211     * including <code>BigInteger</code> values with a
212     * {@link java.math.BigInteger#bitLength() bit length} of less than 64,
213     * and {@link java.lang.Number#doubleValue()} for all other types. It
214     * then calls
215     * {@link #format(long,java.lang.StringBuffer,java.text.FieldPosition)}
216     * or {@link #format(double,java.lang.StringBuffer,java.text.FieldPosition)}.
217     * This may result in loss of magnitude information and precision for
218     * <code>BigInteger</code> and <code>BigDecimal</code> values.
219     * @param number     the number to format
220     * @param toAppendTo the <code>StringBuffer</code> to which the formatted
221     *                   text is to be appended
222     * @param pos        On input: an alignment field, if desired.
223     *                   On output: the offsets of the alignment field.
224     * @return           the value passed in as <code>toAppendTo</code>
225     * @exception        IllegalArgumentException if <code>number</code> is
226     *                   null or not an instance of <code>Number</code>.
227     * @exception        NullPointerException if <code>toAppendTo</code> or
228     *                   <code>pos</code> is null
229     * @exception        ArithmeticException if rounding is needed with rounding
230     *                   mode being set to RoundingMode.UNNECESSARY
231     * @see              java.text.FieldPosition
232     */
233    @Override
234    public StringBuffer format(Object number,
235                               StringBuffer toAppendTo,
236                               FieldPosition pos) {
237        if (number instanceof Long || number instanceof Integer ||
238            number instanceof Short || number instanceof Byte ||
239            number instanceof AtomicInteger || number instanceof AtomicLong ||
240            (number instanceof BigInteger &&
241             ((BigInteger)number).bitLength() < 64)) {
242            return format(((Number)number).longValue(), toAppendTo, pos);
243        } else if (number instanceof Number) {
244            return format(((Number)number).doubleValue(), toAppendTo, pos);
245        } else {
246            throw new IllegalArgumentException("Cannot format given Object as a Number");
247        }
248    }
249
250    /**
251     * Parses text from a string to produce a <code>Number</code>.
252     * <p>
253     * The method attempts to parse text starting at the index given by
254     * <code>pos</code>.
255     * If parsing succeeds, then the index of <code>pos</code> is updated
256     * to the index after the last character used (parsing does not necessarily
257     * use all characters up to the end of the string), and the parsed
258     * number is returned. The updated <code>pos</code> can be used to
259     * indicate the starting point for the next call to this method.
260     * If an error occurs, then the index of <code>pos</code> is not
261     * changed, the error index of <code>pos</code> is set to the index of
262     * the character where the error occurred, and null is returned.
263     * <p>
264     * See the {@link #parse(String, ParsePosition)} method for more information
265     * on number parsing.
266     *
267     * @param source A <code>String</code>, part of which should be parsed.
268     * @param pos A <code>ParsePosition</code> object with index and error
269     *            index information as described above.
270     * @return A <code>Number</code> parsed from the string. In case of
271     *         error, returns null.
272     * @exception NullPointerException if <code>pos</code> is null.
273     */
274    @Override
275    public final Object parseObject(String source, ParsePosition pos) {
276        return parse(source, pos);
277    }
278
279   /**
280     * Specialization of format.
281     *
282     * @param number the double number to format
283     * @return the formatted String
284     * @exception        ArithmeticException if rounding is needed with rounding
285     *                   mode being set to RoundingMode.UNNECESSARY
286     * @see java.text.Format#format
287     */
288    public final String format(double number) {
289        // Android-removed: fast-path code.
290        return format(number, new StringBuffer(),
291                      DontCareFieldPosition.INSTANCE).toString();
292    }
293
294    // Android-removed: fastFormat method.
295
296   /**
297     * Specialization of format.
298     *
299     * @param number the long number to format
300     * @return the formatted String
301     * @exception        ArithmeticException if rounding is needed with rounding
302     *                   mode being set to RoundingMode.UNNECESSARY
303     * @see java.text.Format#format
304     */
305    public final String format(long number) {
306        return format(number, new StringBuffer(),
307                      DontCareFieldPosition.INSTANCE).toString();
308    }
309
310   /**
311     * Specialization of format.
312     *
313     * @param number     the double number to format
314     * @param toAppendTo the StringBuffer to which the formatted text is to be
315     *                   appended
316     * @param pos        the field position
317     * @return the formatted StringBuffer
318     * @exception        ArithmeticException if rounding is needed with rounding
319     *                   mode being set to RoundingMode.UNNECESSARY
320     * @see java.text.Format#format
321     */
322    public abstract StringBuffer format(double number,
323                                        StringBuffer toAppendTo,
324                                        FieldPosition pos);
325
326   /**
327     * Specialization of format.
328     *
329     * @param number     the long number to format
330     * @param toAppendTo the StringBuffer to which the formatted text is to be
331     *                   appended
332     * @param pos        the field position
333     * @return the formatted StringBuffer
334     * @exception        ArithmeticException if rounding is needed with rounding
335     *                   mode being set to RoundingMode.UNNECESSARY
336     * @see java.text.Format#format
337     */
338    public abstract StringBuffer format(long number,
339                                        StringBuffer toAppendTo,
340                                        FieldPosition pos);
341
342   /**
343     * Returns a Long if possible (e.g., within the range [Long.MIN_VALUE,
344     * Long.MAX_VALUE] and with no decimals), otherwise a Double.
345     * If IntegerOnly is set, will stop at a decimal
346     * point (or equivalent; e.g., for rational numbers "1 2/3", will stop
347     * after the 1).
348     * Does not throw an exception; if no object can be parsed, index is
349     * unchanged!
350     *
351     * @param source the String to parse
352     * @param parsePosition the parse position
353     * @return the parsed value
354     * @see java.text.NumberFormat#isParseIntegerOnly
355     * @see java.text.Format#parseObject
356     */
357    public abstract Number parse(String source, ParsePosition parsePosition);
358
359    /**
360     * Parses text from the beginning of the given string to produce a number.
361     * The method may not use the entire text of the given string.
362     * <p>
363     * See the {@link #parse(String, ParsePosition)} method for more information
364     * on number parsing.
365     *
366     * @param source A <code>String</code> whose beginning should be parsed.
367     * @return A <code>Number</code> parsed from the string.
368     * @exception ParseException if the beginning of the specified string
369     *            cannot be parsed.
370     */
371    public Number parse(String source) throws ParseException {
372        ParsePosition parsePosition = new ParsePosition(0);
373        Number result = parse(source, parsePosition);
374        if (parsePosition.index == 0) {
375            throw new ParseException("Unparseable number: \"" + source + "\"",
376                                     parsePosition.errorIndex);
377        }
378        return result;
379    }
380
381    /**
382     * Returns true if this format will parse numbers as integers only.
383     * For example in the English locale, with ParseIntegerOnly true, the
384     * string "1234." would be parsed as the integer value 1234 and parsing
385     * would stop at the "." character.  Of course, the exact format accepted
386     * by the parse operation is locale dependant and determined by sub-classes
387     * of NumberFormat.
388     *
389     * @return {@code true} if numbers should be parsed as integers only;
390     *         {@code false} otherwise
391     */
392    public boolean isParseIntegerOnly() {
393        return parseIntegerOnly;
394    }
395
396    /**
397     * Sets whether or not numbers should be parsed as integers only.
398     *
399     * @param value {@code true} if numbers should be parsed as integers only;
400     *              {@code false} otherwise
401     * @see #isParseIntegerOnly
402     */
403    public void setParseIntegerOnly(boolean value) {
404        parseIntegerOnly = value;
405    }
406
407    //============== Locale Stuff =====================
408
409    /**
410     * Returns a general-purpose number format for the current default
411     * {@link java.util.Locale.Category#FORMAT FORMAT} locale.
412     * This is the same as calling
413     * {@link #getNumberInstance() getNumberInstance()}.
414     *
415     * @return the {@code NumberFormat} instance for general-purpose number
416     * formatting
417     */
418    public final static NumberFormat getInstance() {
419        return getInstance(Locale.getDefault(Locale.Category.FORMAT), NUMBERSTYLE);
420    }
421
422    /**
423     * Returns a general-purpose number format for the specified locale.
424     * This is the same as calling
425     * {@link #getNumberInstance(java.util.Locale) getNumberInstance(inLocale)}.
426     *
427     * @param inLocale the desired locale
428     * @return the {@code NumberFormat} instance for general-purpose number
429     * formatting
430     */
431    public static NumberFormat getInstance(Locale inLocale) {
432        return getInstance(inLocale, NUMBERSTYLE);
433    }
434
435    /**
436     * Returns a general-purpose number format for the current default
437     * {@link java.util.Locale.Category#FORMAT FORMAT} locale.
438     * <p>This is equivalent to calling
439     * {@link #getNumberInstance(Locale)
440     *     getNumberInstance(Locale.getDefault(Locale.Category.FORMAT))}.
441     *
442     * @return the {@code NumberFormat} instance for general-purpose number
443     * formatting
444     * @see java.util.Locale#getDefault(java.util.Locale.Category)
445     * @see java.util.Locale.Category#FORMAT
446     */
447    public final static NumberFormat getNumberInstance() {
448        return getInstance(Locale.getDefault(Locale.Category.FORMAT), NUMBERSTYLE);
449    }
450
451    /**
452     * Returns a general-purpose number format for the specified locale.
453     *
454     * @param inLocale the desired locale
455     * @return the {@code NumberFormat} instance for general-purpose number
456     * formatting
457     */
458    public static NumberFormat getNumberInstance(Locale inLocale) {
459        return getInstance(inLocale, NUMBERSTYLE);
460    }
461
462    /**
463     * Returns an integer number format for the current default
464     * {@link java.util.Locale.Category#FORMAT FORMAT} locale. The
465     * returned number format is configured to round floating point numbers
466     * to the nearest integer using half-even rounding (see {@link
467     * java.math.RoundingMode#HALF_EVEN RoundingMode.HALF_EVEN}) for formatting,
468     * and to parse only the integer part of an input string (see {@link
469     * #isParseIntegerOnly isParseIntegerOnly}).
470     * <p>This is equivalent to calling
471     * {@link #getIntegerInstance(Locale)
472     *     getIntegerInstance(Locale.getDefault(Locale.Category.FORMAT))}.
473     *
474     * @see #getRoundingMode()
475     * @see java.util.Locale#getDefault(java.util.Locale.Category)
476     * @see java.util.Locale.Category#FORMAT
477     * @return a number format for integer values
478     * @since 1.4
479     */
480    public final static NumberFormat getIntegerInstance() {
481        return getInstance(Locale.getDefault(Locale.Category.FORMAT), INTEGERSTYLE);
482    }
483
484    /**
485     * Returns an integer number format for the specified locale. The
486     * returned number format is configured to round floating point numbers
487     * to the nearest integer using half-even rounding (see {@link
488     * java.math.RoundingMode#HALF_EVEN RoundingMode.HALF_EVEN}) for formatting,
489     * and to parse only the integer part of an input string (see {@link
490     * #isParseIntegerOnly isParseIntegerOnly}).
491     *
492     * @param inLocale the desired locale
493     * @see #getRoundingMode()
494     * @return a number format for integer values
495     * @since 1.4
496     */
497    public static NumberFormat getIntegerInstance(Locale inLocale) {
498        return getInstance(inLocale, INTEGERSTYLE);
499    }
500
501    /**
502     * Returns a currency format for the current default
503     * {@link java.util.Locale.Category#FORMAT FORMAT} locale.
504     * <p>This is equivalent to calling
505     * {@link #getCurrencyInstance(Locale)
506     *     getCurrencyInstance(Locale.getDefault(Locale.Category.FORMAT))}.
507     *
508     * @return the {@code NumberFormat} instance for currency formatting
509     * @see java.util.Locale#getDefault(java.util.Locale.Category)
510     * @see java.util.Locale.Category#FORMAT
511     */
512    public final static NumberFormat getCurrencyInstance() {
513        return getInstance(Locale.getDefault(Locale.Category.FORMAT), CURRENCYSTYLE);
514    }
515
516    /**
517     * Returns a currency format for the specified locale.
518     *
519     * @param inLocale the desired locale
520     * @return the {@code NumberFormat} instance for currency formatting
521     */
522    public static NumberFormat getCurrencyInstance(Locale inLocale) {
523        return getInstance(inLocale, CURRENCYSTYLE);
524    }
525
526    /**
527     * Returns a percentage format for the current default
528     * {@link java.util.Locale.Category#FORMAT FORMAT} locale.
529     * <p>This is equivalent to calling
530     * {@link #getPercentInstance(Locale)
531     *     getPercentInstance(Locale.getDefault(Locale.Category.FORMAT))}.
532     *
533     * @return the {@code NumberFormat} instance for percentage formatting
534     * @see java.util.Locale#getDefault(java.util.Locale.Category)
535     * @see java.util.Locale.Category#FORMAT
536     */
537    public final static NumberFormat getPercentInstance() {
538        return getInstance(Locale.getDefault(Locale.Category.FORMAT), PERCENTSTYLE);
539    }
540
541    /**
542     * Returns a percentage format for the specified locale.
543     *
544     * @param inLocale the desired locale
545     * @return the {@code NumberFormat} instance for percentage formatting
546     */
547    public static NumberFormat getPercentInstance(Locale inLocale) {
548        return getInstance(inLocale, PERCENTSTYLE);
549    }
550
551    // Android-removed: non-API methods getScientificInstance([Locale]).
552
553    // Android-changed: Removed reference to NumberFormatProvider.
554    /**
555     * Returns an array of all locales for which the
556     * <code>get*Instance</code> methods of this class can return
557     * localized instances.
558     *
559     * @return An array of locales for which localized
560     *         <code>NumberFormat</code> instances are available.
561     */
562    public static Locale[] getAvailableLocales() {
563        // Android-changed: Removed used of NumberFormatProvider. Switched to use ICU.
564        return ICU.getAvailableLocales();
565    }
566
567    /**
568     * Overrides hashCode.
569     */
570    @Override
571    public int hashCode() {
572        return maximumIntegerDigits * 37 + maxFractionDigits;
573        // just enough fields for a reasonable distribution
574    }
575
576    /**
577     * Overrides equals.
578     */
579    @Override
580    public boolean equals(Object obj) {
581        if (obj == null) {
582            return false;
583        }
584        if (this == obj) {
585            return true;
586        }
587        if (getClass() != obj.getClass()) {
588            return false;
589        }
590        NumberFormat other = (NumberFormat) obj;
591        return (maximumIntegerDigits == other.maximumIntegerDigits
592            && minimumIntegerDigits == other.minimumIntegerDigits
593            && maximumFractionDigits == other.maximumFractionDigits
594            && minimumFractionDigits == other.minimumFractionDigits
595            && groupingUsed == other.groupingUsed
596            && parseIntegerOnly == other.parseIntegerOnly);
597    }
598
599    /**
600     * Overrides Cloneable.
601     */
602    @Override
603    public Object clone() {
604        NumberFormat other = (NumberFormat) super.clone();
605        return other;
606    }
607
608    /**
609     * Returns true if grouping is used in this format. For example, in the
610     * English locale, with grouping on, the number 1234567 might be formatted
611     * as "1,234,567". The grouping separator as well as the size of each group
612     * is locale dependant and is determined by sub-classes of NumberFormat.
613     *
614     * @return {@code true} if grouping is used;
615     *         {@code false} otherwise
616     * @see #setGroupingUsed
617     */
618    public boolean isGroupingUsed() {
619        return groupingUsed;
620    }
621
622    /**
623     * Set whether or not grouping will be used in this format.
624     *
625     * @param newValue {@code true} if grouping is used;
626     *                 {@code false} otherwise
627     * @see #isGroupingUsed
628     */
629    public void setGroupingUsed(boolean newValue) {
630        groupingUsed = newValue;
631    }
632
633    /**
634     * Returns the maximum number of digits allowed in the integer portion of a
635     * number.
636     *
637     * @return the maximum number of digits
638     * @see #setMaximumIntegerDigits
639     */
640    public int getMaximumIntegerDigits() {
641        return maximumIntegerDigits;
642    }
643
644    /**
645     * Sets the maximum number of digits allowed in the integer portion of a
646     * number. maximumIntegerDigits must be &ge; minimumIntegerDigits.  If the
647     * new value for maximumIntegerDigits is less than the current value
648     * of minimumIntegerDigits, then minimumIntegerDigits will also be set to
649     * the new value.
650     *
651     * @param newValue the maximum number of integer digits to be shown; if
652     * less than zero, then zero is used. The concrete subclass may enforce an
653     * upper limit to this value appropriate to the numeric type being formatted.
654     * @see #getMaximumIntegerDigits
655     */
656    public void setMaximumIntegerDigits(int newValue) {
657        maximumIntegerDigits = Math.max(0,newValue);
658        if (minimumIntegerDigits > maximumIntegerDigits) {
659            minimumIntegerDigits = maximumIntegerDigits;
660        }
661    }
662
663    /**
664     * Returns the minimum number of digits allowed in the integer portion of a
665     * number.
666     *
667     * @return the minimum number of digits
668     * @see #setMinimumIntegerDigits
669     */
670    public int getMinimumIntegerDigits() {
671        return minimumIntegerDigits;
672    }
673
674    /**
675     * Sets the minimum number of digits allowed in the integer portion of a
676     * number. minimumIntegerDigits must be &le; maximumIntegerDigits.  If the
677     * new value for minimumIntegerDigits exceeds the current value
678     * of maximumIntegerDigits, then maximumIntegerDigits will also be set to
679     * the new value
680     *
681     * @param newValue the minimum number of integer digits to be shown; if
682     * less than zero, then zero is used. The concrete subclass may enforce an
683     * upper limit to this value appropriate to the numeric type being formatted.
684     * @see #getMinimumIntegerDigits
685     */
686    public void setMinimumIntegerDigits(int newValue) {
687        minimumIntegerDigits = Math.max(0,newValue);
688        if (minimumIntegerDigits > maximumIntegerDigits) {
689            maximumIntegerDigits = minimumIntegerDigits;
690        }
691    }
692
693    /**
694     * Returns the maximum number of digits allowed in the fraction portion of a
695     * number.
696     *
697     * @return the maximum number of digits.
698     * @see #setMaximumFractionDigits
699     */
700    public int getMaximumFractionDigits() {
701        return maximumFractionDigits;
702    }
703
704    /**
705     * Sets the maximum number of digits allowed in the fraction portion of a
706     * number. maximumFractionDigits must be &ge; minimumFractionDigits.  If the
707     * new value for maximumFractionDigits is less than the current value
708     * of minimumFractionDigits, then minimumFractionDigits will also be set to
709     * the new value.
710     *
711     * @param newValue the maximum number of fraction digits to be shown; if
712     * less than zero, then zero is used. The concrete subclass may enforce an
713     * upper limit to this value appropriate to the numeric type being formatted.
714     * @see #getMaximumFractionDigits
715     */
716    public void setMaximumFractionDigits(int newValue) {
717        maximumFractionDigits = Math.max(0,newValue);
718        if (maximumFractionDigits < minimumFractionDigits) {
719            minimumFractionDigits = maximumFractionDigits;
720        }
721    }
722
723    /**
724     * Returns the minimum number of digits allowed in the fraction portion of a
725     * number.
726     *
727     * @return the minimum number of digits
728     * @see #setMinimumFractionDigits
729     */
730    public int getMinimumFractionDigits() {
731        return minimumFractionDigits;
732    }
733
734    /**
735     * Sets the minimum number of digits allowed in the fraction portion of a
736     * number. minimumFractionDigits must be &le; maximumFractionDigits.  If the
737     * new value for minimumFractionDigits exceeds the current value
738     * of maximumFractionDigits, then maximumIntegerDigits will also be set to
739     * the new value
740     *
741     * @param newValue the minimum number of fraction digits to be shown; if
742     * less than zero, then zero is used. The concrete subclass may enforce an
743     * upper limit to this value appropriate to the numeric type being formatted.
744     * @see #getMinimumFractionDigits
745     */
746    public void setMinimumFractionDigits(int newValue) {
747        minimumFractionDigits = Math.max(0,newValue);
748        if (maximumFractionDigits < minimumFractionDigits) {
749            maximumFractionDigits = minimumFractionDigits;
750        }
751    }
752
753    /**
754     * Gets the currency used by this number format when formatting
755     * currency values. The initial value is derived in a locale dependent
756     * way. The returned value may be null if no valid
757     * currency could be determined and no currency has been set using
758     * {@link #setCurrency(java.util.Currency) setCurrency}.
759     * <p>
760     * The default implementation throws
761     * <code>UnsupportedOperationException</code>.
762     *
763     * @return the currency used by this number format, or <code>null</code>
764     * @exception UnsupportedOperationException if the number format class
765     * doesn't implement currency formatting
766     * @since 1.4
767     */
768    public Currency getCurrency() {
769        throw new UnsupportedOperationException();
770    }
771
772    /**
773     * Sets the currency used by this number format when formatting
774     * currency values. This does not update the minimum or maximum
775     * number of fraction digits used by the number format.
776     * <p>
777     * The default implementation throws
778     * <code>UnsupportedOperationException</code>.
779     *
780     * @param currency the new currency to be used by this number format
781     * @exception UnsupportedOperationException if the number format class
782     * doesn't implement currency formatting
783     * @exception NullPointerException if <code>currency</code> is null
784     * @since 1.4
785     */
786    public void setCurrency(Currency currency) {
787        throw new UnsupportedOperationException();
788    }
789
790    /**
791     * Gets the {@link java.math.RoundingMode} used in this NumberFormat.
792     * The default implementation of this method in NumberFormat
793     * always throws {@link java.lang.UnsupportedOperationException}.
794     * Subclasses which handle different rounding modes should override
795     * this method.
796     *
797     * @exception UnsupportedOperationException The default implementation
798     *     always throws this exception
799     * @return The <code>RoundingMode</code> used for this NumberFormat.
800     * @see #setRoundingMode(RoundingMode)
801     * @since 1.6
802     */
803    public RoundingMode getRoundingMode() {
804        throw new UnsupportedOperationException();
805    }
806
807    /**
808     * Sets the {@link java.math.RoundingMode} used in this NumberFormat.
809     * The default implementation of this method in NumberFormat always
810     * throws {@link java.lang.UnsupportedOperationException}.
811     * Subclasses which handle different rounding modes should override
812     * this method.
813     *
814     * @exception UnsupportedOperationException The default implementation
815     *     always throws this exception
816     * @exception NullPointerException if <code>roundingMode</code> is null
817     * @param roundingMode The <code>RoundingMode</code> to be used
818     * @see #getRoundingMode()
819     * @since 1.6
820     */
821    public void setRoundingMode(RoundingMode roundingMode) {
822        throw new UnsupportedOperationException();
823    }
824
825    // =======================privates===============================
826
827    private static NumberFormat getInstance(Locale desiredLocale,
828                                           int choice) {
829        // BEGIN Android-changed: Removed use of NumberFormatProvider. Switched to use ICU.
830        /*
831        LocaleProviderAdapter adapter;
832        adapter = LocaleProviderAdapter.getAdapter(NumberFormatProvider.class,
833                                                   desiredLocale);
834        NumberFormat numberFormat = getInstance(adapter, desiredLocale, choice);
835        if (numberFormat == null) {
836            numberFormat = getInstance(LocaleProviderAdapter.forJRE(),
837                                       desiredLocale, choice);
838        */
839        String[] numberPatterns = new String[3];
840        LocaleData data = LocaleData.get(desiredLocale);
841        numberPatterns[NUMBERSTYLE] = data.numberPattern;
842        numberPatterns[CURRENCYSTYLE] = data.currencyPattern;
843        numberPatterns[PERCENTSTYLE] = data.percentPattern;
844
845        // Note: the following lines are from NumberFormatProviderImpl upstream.
846        DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(desiredLocale);
847        int entry = (choice == INTEGERSTYLE) ? NUMBERSTYLE : choice;
848        DecimalFormat numberFormat = new DecimalFormat(numberPatterns[entry], symbols);
849
850        if (choice == INTEGERSTYLE) {
851            numberFormat.setMaximumFractionDigits(0);
852            numberFormat.setDecimalSeparatorAlwaysShown(false);
853            numberFormat.setParseIntegerOnly(true);
854        } else if (choice == CURRENCYSTYLE) {
855            numberFormat.adjustForCurrencyDefaultFractionDigits();
856        }
857        // END Android-changed: Removed use of NumberFormatProvider. Switched to use ICU.
858        return numberFormat;
859    }
860
861    /**
862     * First, read in the default serializable data.
863     *
864     * Then, if <code>serialVersionOnStream</code> is less than 1, indicating that
865     * the stream was written by JDK 1.1,
866     * set the <code>int</code> fields such as <code>maximumIntegerDigits</code>
867     * to be equal to the <code>byte</code> fields such as <code>maxIntegerDigits</code>,
868     * since the <code>int</code> fields were not present in JDK 1.1.
869     * Finally, set serialVersionOnStream back to the maximum allowed value so that
870     * default serialization will work properly if this object is streamed out again.
871     *
872     * <p>If <code>minimumIntegerDigits</code> is greater than
873     * <code>maximumIntegerDigits</code> or <code>minimumFractionDigits</code>
874     * is greater than <code>maximumFractionDigits</code>, then the stream data
875     * is invalid and this method throws an <code>InvalidObjectException</code>.
876     * In addition, if any of these values is negative, then this method throws
877     * an <code>InvalidObjectException</code>.
878     *
879     * @since 1.2
880     */
881    private void readObject(ObjectInputStream stream)
882         throws IOException, ClassNotFoundException
883    {
884        stream.defaultReadObject();
885        if (serialVersionOnStream < 1) {
886            // Didn't have additional int fields, reassign to use them.
887            maximumIntegerDigits = maxIntegerDigits;
888            minimumIntegerDigits = minIntegerDigits;
889            maximumFractionDigits = maxFractionDigits;
890            minimumFractionDigits = minFractionDigits;
891        }
892        if (minimumIntegerDigits > maximumIntegerDigits ||
893            minimumFractionDigits > maximumFractionDigits ||
894            minimumIntegerDigits < 0 || minimumFractionDigits < 0) {
895            throw new InvalidObjectException("Digit count range invalid");
896        }
897        serialVersionOnStream = currentSerialVersion;
898    }
899
900    /**
901     * Write out the default serializable data, after first setting
902     * the <code>byte</code> fields such as <code>maxIntegerDigits</code> to be
903     * equal to the <code>int</code> fields such as <code>maximumIntegerDigits</code>
904     * (or to <code>Byte.MAX_VALUE</code>, whichever is smaller), for compatibility
905     * with the JDK 1.1 version of the stream format.
906     *
907     * @since 1.2
908     */
909    private void writeObject(ObjectOutputStream stream)
910         throws IOException
911    {
912        maxIntegerDigits = (maximumIntegerDigits > Byte.MAX_VALUE) ?
913                           Byte.MAX_VALUE : (byte)maximumIntegerDigits;
914        minIntegerDigits = (minimumIntegerDigits > Byte.MAX_VALUE) ?
915                           Byte.MAX_VALUE : (byte)minimumIntegerDigits;
916        maxFractionDigits = (maximumFractionDigits > Byte.MAX_VALUE) ?
917                            Byte.MAX_VALUE : (byte)maximumFractionDigits;
918        minFractionDigits = (minimumFractionDigits > Byte.MAX_VALUE) ?
919                            Byte.MAX_VALUE : (byte)minimumFractionDigits;
920        stream.defaultWriteObject();
921    }
922
923    // Constants used by factory methods to specify a style of format.
924    private static final int NUMBERSTYLE = 0;
925    private static final int CURRENCYSTYLE = 1;
926    private static final int PERCENTSTYLE = 2;
927    // Android-changed: changed: removed SCIENTIFICSTYLE and pull down INTEGERSTYLE value.
928    //private static final int SCIENTIFICSTYLE = 3;
929    private static final int INTEGERSTYLE = 3;
930
931    /**
932     * True if the grouping (i.e. thousands) separator is used when
933     * formatting and parsing numbers.
934     *
935     * @serial
936     * @see #isGroupingUsed
937     */
938    private boolean groupingUsed = true;
939
940    /**
941     * The maximum number of digits allowed in the integer portion of a
942     * number.  <code>maxIntegerDigits</code> must be greater than or equal to
943     * <code>minIntegerDigits</code>.
944     * <p>
945     * <strong>Note:</strong> This field exists only for serialization
946     * compatibility with JDK 1.1.  In Java platform 2 v1.2 and higher, the new
947     * <code>int</code> field <code>maximumIntegerDigits</code> is used instead.
948     * When writing to a stream, <code>maxIntegerDigits</code> is set to
949     * <code>maximumIntegerDigits</code> or <code>Byte.MAX_VALUE</code>,
950     * whichever is smaller.  When reading from a stream, this field is used
951     * only if <code>serialVersionOnStream</code> is less than 1.
952     *
953     * @serial
954     * @see #getMaximumIntegerDigits
955     */
956    private byte    maxIntegerDigits = 40;
957
958    /**
959     * The minimum number of digits allowed in the integer portion of a
960     * number.  <code>minimumIntegerDigits</code> must be less than or equal to
961     * <code>maximumIntegerDigits</code>.
962     * <p>
963     * <strong>Note:</strong> This field exists only for serialization
964     * compatibility with JDK 1.1.  In Java platform 2 v1.2 and higher, the new
965     * <code>int</code> field <code>minimumIntegerDigits</code> is used instead.
966     * When writing to a stream, <code>minIntegerDigits</code> is set to
967     * <code>minimumIntegerDigits</code> or <code>Byte.MAX_VALUE</code>,
968     * whichever is smaller.  When reading from a stream, this field is used
969     * only if <code>serialVersionOnStream</code> is less than 1.
970     *
971     * @serial
972     * @see #getMinimumIntegerDigits
973     */
974    private byte    minIntegerDigits = 1;
975
976    /**
977     * The maximum number of digits allowed in the fractional portion of a
978     * number.  <code>maximumFractionDigits</code> must be greater than or equal to
979     * <code>minimumFractionDigits</code>.
980     * <p>
981     * <strong>Note:</strong> This field exists only for serialization
982     * compatibility with JDK 1.1.  In Java platform 2 v1.2 and higher, the new
983     * <code>int</code> field <code>maximumFractionDigits</code> is used instead.
984     * When writing to a stream, <code>maxFractionDigits</code> is set to
985     * <code>maximumFractionDigits</code> or <code>Byte.MAX_VALUE</code>,
986     * whichever is smaller.  When reading from a stream, this field is used
987     * only if <code>serialVersionOnStream</code> is less than 1.
988     *
989     * @serial
990     * @see #getMaximumFractionDigits
991     */
992    private byte    maxFractionDigits = 3;    // invariant, >= minFractionDigits
993
994    /**
995     * The minimum number of digits allowed in the fractional portion of a
996     * number.  <code>minimumFractionDigits</code> must be less than or equal to
997     * <code>maximumFractionDigits</code>.
998     * <p>
999     * <strong>Note:</strong> This field exists only for serialization
1000     * compatibility with JDK 1.1.  In Java platform 2 v1.2 and higher, the new
1001     * <code>int</code> field <code>minimumFractionDigits</code> is used instead.
1002     * When writing to a stream, <code>minFractionDigits</code> is set to
1003     * <code>minimumFractionDigits</code> or <code>Byte.MAX_VALUE</code>,
1004     * whichever is smaller.  When reading from a stream, this field is used
1005     * only if <code>serialVersionOnStream</code> is less than 1.
1006     *
1007     * @serial
1008     * @see #getMinimumFractionDigits
1009     */
1010    private byte    minFractionDigits = 0;
1011
1012    /**
1013     * True if this format will parse numbers as integers only.
1014     *
1015     * @serial
1016     * @see #isParseIntegerOnly
1017     */
1018    private boolean parseIntegerOnly = false;
1019
1020    // new fields for 1.2.  byte is too small for integer digits.
1021
1022    /**
1023     * The maximum number of digits allowed in the integer portion of a
1024     * number.  <code>maximumIntegerDigits</code> must be greater than or equal to
1025     * <code>minimumIntegerDigits</code>.
1026     *
1027     * @serial
1028     * @since 1.2
1029     * @see #getMaximumIntegerDigits
1030     */
1031    private int    maximumIntegerDigits = 40;
1032
1033    /**
1034     * The minimum number of digits allowed in the integer portion of a
1035     * number.  <code>minimumIntegerDigits</code> must be less than or equal to
1036     * <code>maximumIntegerDigits</code>.
1037     *
1038     * @serial
1039     * @since 1.2
1040     * @see #getMinimumIntegerDigits
1041     */
1042    private int    minimumIntegerDigits = 1;
1043
1044    /**
1045     * The maximum number of digits allowed in the fractional portion of a
1046     * number.  <code>maximumFractionDigits</code> must be greater than or equal to
1047     * <code>minimumFractionDigits</code>.
1048     *
1049     * @serial
1050     * @since 1.2
1051     * @see #getMaximumFractionDigits
1052     */
1053    private int    maximumFractionDigits = 3;    // invariant, >= minFractionDigits
1054
1055    /**
1056     * The minimum number of digits allowed in the fractional portion of a
1057     * number.  <code>minimumFractionDigits</code> must be less than or equal to
1058     * <code>maximumFractionDigits</code>.
1059     *
1060     * @serial
1061     * @since 1.2
1062     * @see #getMinimumFractionDigits
1063     */
1064    private int    minimumFractionDigits = 0;
1065
1066    static final int currentSerialVersion = 1;
1067
1068    /**
1069     * Describes the version of <code>NumberFormat</code> present on the stream.
1070     * Possible values are:
1071     * <ul>
1072     * <li><b>0</b> (or uninitialized): the JDK 1.1 version of the stream format.
1073     *     In this version, the <code>int</code> fields such as
1074     *     <code>maximumIntegerDigits</code> were not present, and the <code>byte</code>
1075     *     fields such as <code>maxIntegerDigits</code> are used instead.
1076     *
1077     * <li><b>1</b>: the 1.2 version of the stream format.  The values of the
1078     *     <code>byte</code> fields such as <code>maxIntegerDigits</code> are ignored,
1079     *     and the <code>int</code> fields such as <code>maximumIntegerDigits</code>
1080     *     are used instead.
1081     * </ul>
1082     * When streaming out a <code>NumberFormat</code>, the most recent format
1083     * (corresponding to the highest allowable <code>serialVersionOnStream</code>)
1084     * is always written.
1085     *
1086     * @serial
1087     * @since 1.2
1088     */
1089    private int serialVersionOnStream = currentSerialVersion;
1090
1091    // Removed "implements Cloneable" clause.  Needs to update serialization
1092    // ID for backward compatibility.
1093    static final long serialVersionUID = -2308460125733713944L;
1094
1095
1096    //
1097    // class for AttributedCharacterIterator attributes
1098    //
1099    /**
1100     * Defines constants that are used as attribute keys in the
1101     * <code>AttributedCharacterIterator</code> returned
1102     * from <code>NumberFormat.formatToCharacterIterator</code> and as
1103     * field identifiers in <code>FieldPosition</code>.
1104     *
1105     * @since 1.4
1106     */
1107    public static class Field extends Format.Field {
1108
1109        // Proclaim serial compatibility with 1.4 FCS
1110        private static final long serialVersionUID = 7494728892700160890L;
1111
1112        // table of all instances in this class, used by readResolve
1113        private static final Map<String, Field> instanceMap = new HashMap<>(11);
1114
1115        /**
1116         * Creates a Field instance with the specified
1117         * name.
1118         *
1119         * @param name Name of the attribute
1120         */
1121        protected Field(String name) {
1122            super(name);
1123            if (this.getClass() == NumberFormat.Field.class) {
1124                instanceMap.put(name, this);
1125            }
1126        }
1127
1128        /**
1129         * Resolves instances being deserialized to the predefined constants.
1130         *
1131         * @throws InvalidObjectException if the constant could not be resolved.
1132         * @return resolved NumberFormat.Field constant
1133         */
1134        @Override
1135        protected Object readResolve() throws InvalidObjectException {
1136            if (this.getClass() != NumberFormat.Field.class) {
1137                throw new InvalidObjectException("subclass didn't correctly implement readResolve");
1138            }
1139
1140            Object instance = instanceMap.get(getName());
1141            if (instance != null) {
1142                return instance;
1143            } else {
1144                throw new InvalidObjectException("unknown attribute name");
1145            }
1146        }
1147
1148        /**
1149         * Constant identifying the integer field.
1150         */
1151        public static final Field INTEGER = new Field("integer");
1152
1153        /**
1154         * Constant identifying the fraction field.
1155         */
1156        public static final Field FRACTION = new Field("fraction");
1157
1158        /**
1159         * Constant identifying the exponent field.
1160         */
1161        public static final Field EXPONENT = new Field("exponent");
1162
1163        /**
1164         * Constant identifying the decimal separator field.
1165         */
1166        public static final Field DECIMAL_SEPARATOR =
1167                            new Field("decimal separator");
1168
1169        /**
1170         * Constant identifying the sign field.
1171         */
1172        public static final Field SIGN = new Field("sign");
1173
1174        /**
1175         * Constant identifying the grouping separator field.
1176         */
1177        public static final Field GROUPING_SEPARATOR =
1178                            new Field("grouping separator");
1179
1180        /**
1181         * Constant identifying the exponent symbol field.
1182         */
1183        public static final Field EXPONENT_SYMBOL = new
1184                            Field("exponent symbol");
1185
1186        /**
1187         * Constant identifying the percent field.
1188         */
1189        public static final Field PERCENT = new Field("percent");
1190
1191        /**
1192         * Constant identifying the permille field.
1193         */
1194        public static final Field PERMILLE = new Field("per mille");
1195
1196        /**
1197         * Constant identifying the currency field.
1198         */
1199        public static final Field CURRENCY = new Field("currency");
1200
1201        /**
1202         * Constant identifying the exponent sign field.
1203         */
1204        public static final Field EXPONENT_SIGN = new Field("exponent sign");
1205    }
1206}
1207