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