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