< prev index next >

src/java.base/share/classes/java/text/NumberFormat.java

Print this page


   1 /*
   2  * Copyright (c) 1996, 2017, 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


  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>{@code


  95  * <pre>{@code
  96  * NumberFormat nf = NumberFormat.getInstance(Locale.FRENCH);
  97  * }</pre>
  98  * </blockquote>
  99  *
 100  * <p>If the locale contains "nu" (numbers) and/or "rg" (region override)
 101  * <a href="../util/Locale.html#def_locale_extension">Unicode extensions</a>,
 102  * the decimal digits, and/or the country used for formatting are overridden.
 103  * If both "nu" and "rg" are specified, the decimal digits from the "nu"
 104  * extension supersedes the implicit one from the "rg" extension.
 105  *
 106  * <p>You can also use a {@code NumberFormat} to parse numbers:
 107  * <blockquote>
 108  * <pre>{@code
 109  * myNumber = nf.parse(myString);
 110  * }</pre>
 111  * </blockquote>
 112  * Use <code>getInstance</code> or <code>getNumberInstance</code> to get the
 113  * normal number format. Use <code>getIntegerInstance</code> to get an
 114  * integer number format. Use <code>getCurrencyInstance</code> to get the
 115  * currency number format. And use <code>getPercentInstance</code> to get a
 116  * format for displaying percentages. With this format, a fraction like
 117  * 0.53 is displayed as 53%.



 118  *
 119  * <p>
 120  * You can also control the display of numbers with such methods as
 121  * <code>setMinimumFractionDigits</code>.
 122  * If you want even more control over the format or parsing,
 123  * or want to give your users more control,
 124  * you can try casting the <code>NumberFormat</code> you get from the factory methods
 125  * to a <code>DecimalFormat</code>. This will work for the vast majority
 126  * of locales; just remember to put it in a <code>try</code> block in case you
 127  * encounter an unusual one.

 128  *
 129  * <p>
 130  * NumberFormat and DecimalFormat are designed such that some controls
 131  * work for formatting and others work for parsing.  The following is
 132  * the detailed description for each these control methods,
 133  * <p>
 134  * setParseIntegerOnly : only affects parsing, e.g.
 135  * if true,  "3456.78" &rarr; 3456 (and leaves the parse position just after index 6)
 136  * if false, "3456.78" &rarr; 3456.78 (and leaves the parse position just after index 8)
 137  * This is independent of formatting.  If you want to not show a decimal point
 138  * where there might be no digits after the decimal point, use
 139  * setDecimalSeparatorAlwaysShown.
 140  * <p>
 141  * setDecimalSeparatorAlwaysShown : only affects formatting, and only where
 142  * there might be no digits after the decimal point, such as with a pattern
 143  * like "#,##0.##", e.g.,
 144  * if true,  3456.00 &rarr; "3,456."
 145  * if false, 3456.00 &rarr; "3456"
 146  * This is independent of parsing.  If you want parsing to stop at the decimal
 147  * point, use setParseIntegerOnly.


 184  * @implSpec The {@link #format(double, StringBuffer, FieldPosition)},
 185  * {@link #format(long, StringBuffer, FieldPosition)} and
 186  * {@link #parse(String, ParsePosition)} methods may throw
 187  * {@code NullPointerException}, if any of their parameter is {@code null}.
 188  * The subclass may provide its own implementation and specification about
 189  * {@code NullPointerException}.
 190  *
 191  * <p>
 192  * The default implementation provides rounding modes defined
 193  * in {@link java.math.RoundingMode} for formatting numbers. It
 194  * uses the {@linkplain java.math.RoundingMode#HALF_EVEN
 195  * round half-even algorithm}. To change the rounding mode use
 196  * {@link #setRoundingMode(java.math.RoundingMode) setRoundingMode}.
 197  * The {@code NumberFormat} returned by the static factory methods is
 198  * configured to round floating point numbers using half-even
 199  * rounding (see {@link java.math.RoundingMode#HALF_EVEN
 200  * RoundingMode.HALF_EVEN}) for formatting.
 201  *
 202  * @see          DecimalFormat
 203  * @see          ChoiceFormat

 204  * @author       Mark Davis
 205  * @author       Helena Shih
 206  * @since 1.1
 207  */
 208 public abstract class NumberFormat extends Format  {
 209 
 210     /**
 211      * Field constant used to construct a FieldPosition object. Signifies that
 212      * the position of the integer part of a formatted number should be returned.
 213      * @see java.text.FieldPosition
 214      */
 215     public static final int INTEGER_FIELD = 0;
 216 
 217     /**
 218      * Field constant used to construct a FieldPosition object. Signifies that
 219      * the position of the fraction part of a formatted number should be returned.
 220      * @see java.text.FieldPosition
 221      */
 222     public static final int FRACTION_FIELD = 1;
 223 


 455      * @param value {@code true} if numbers should be parsed as integers only;
 456      *              {@code false} otherwise
 457      * @see #isParseIntegerOnly
 458      */
 459     public void setParseIntegerOnly(boolean value) {
 460         parseIntegerOnly = value;
 461     }
 462 
 463     //============== Locale Stuff =====================
 464 
 465     /**
 466      * Returns a general-purpose number format for the current default
 467      * {@link java.util.Locale.Category#FORMAT FORMAT} locale.
 468      * This is the same as calling
 469      * {@link #getNumberInstance() getNumberInstance()}.
 470      *
 471      * @return the {@code NumberFormat} instance for general-purpose number
 472      * formatting
 473      */
 474     public static final NumberFormat getInstance() {
 475         return getInstance(Locale.getDefault(Locale.Category.FORMAT), NUMBERSTYLE);
 476     }
 477 
 478     /**
 479      * Returns a general-purpose number format for the specified locale.
 480      * This is the same as calling
 481      * {@link #getNumberInstance(java.util.Locale) getNumberInstance(inLocale)}.
 482      *
 483      * @param inLocale the desired locale
 484      * @return the {@code NumberFormat} instance for general-purpose number
 485      * formatting
 486      */
 487     public static NumberFormat getInstance(Locale inLocale) {
 488         return getInstance(inLocale, NUMBERSTYLE);
 489     }
 490 
 491     /**
 492      * Returns a general-purpose number format for the current default
 493      * {@link java.util.Locale.Category#FORMAT FORMAT} locale.
 494      * <p>This is equivalent to calling
 495      * {@link #getNumberInstance(Locale)
 496      *     getNumberInstance(Locale.getDefault(Locale.Category.FORMAT))}.
 497      *
 498      * @return the {@code NumberFormat} instance for general-purpose number
 499      * formatting
 500      * @see java.util.Locale#getDefault(java.util.Locale.Category)
 501      * @see java.util.Locale.Category#FORMAT
 502      */
 503     public static final NumberFormat getNumberInstance() {
 504         return getInstance(Locale.getDefault(Locale.Category.FORMAT), NUMBERSTYLE);
 505     }
 506 
 507     /**
 508      * Returns a general-purpose number format for the specified locale.
 509      *
 510      * @param inLocale the desired locale
 511      * @return the {@code NumberFormat} instance for general-purpose number
 512      * formatting
 513      */
 514     public static NumberFormat getNumberInstance(Locale inLocale) {
 515         return getInstance(inLocale, NUMBERSTYLE);
 516     }
 517 
 518     /**
 519      * Returns an integer number format for the current default
 520      * {@link java.util.Locale.Category#FORMAT FORMAT} locale. The
 521      * returned number format is configured to round floating point numbers
 522      * to the nearest integer using half-even rounding (see {@link
 523      * java.math.RoundingMode#HALF_EVEN RoundingMode.HALF_EVEN}) for formatting,
 524      * and to parse only the integer part of an input string (see {@link
 525      * #isParseIntegerOnly isParseIntegerOnly}).
 526      * <p>This is equivalent to calling
 527      * {@link #getIntegerInstance(Locale)
 528      *     getIntegerInstance(Locale.getDefault(Locale.Category.FORMAT))}.
 529      *
 530      * @see #getRoundingMode()
 531      * @see java.util.Locale#getDefault(java.util.Locale.Category)
 532      * @see java.util.Locale.Category#FORMAT
 533      * @return a number format for integer values
 534      * @since 1.4
 535      */
 536     public static final NumberFormat getIntegerInstance() {
 537         return getInstance(Locale.getDefault(Locale.Category.FORMAT), INTEGERSTYLE);
 538     }
 539 
 540     /**
 541      * Returns an integer number format for the specified locale. The
 542      * returned number format is configured to round floating point numbers
 543      * to the nearest integer using half-even rounding (see {@link
 544      * java.math.RoundingMode#HALF_EVEN RoundingMode.HALF_EVEN}) for formatting,
 545      * and to parse only the integer part of an input string (see {@link
 546      * #isParseIntegerOnly isParseIntegerOnly}).
 547      *
 548      * @param inLocale the desired locale
 549      * @see #getRoundingMode()
 550      * @return a number format for integer values
 551      * @since 1.4
 552      */
 553     public static NumberFormat getIntegerInstance(Locale inLocale) {
 554         return getInstance(inLocale, INTEGERSTYLE);
 555     }
 556 
 557     /**
 558      * Returns a currency format for the current default
 559      * {@link java.util.Locale.Category#FORMAT FORMAT} locale.
 560      * <p>This is equivalent to calling
 561      * {@link #getCurrencyInstance(Locale)
 562      *     getCurrencyInstance(Locale.getDefault(Locale.Category.FORMAT))}.
 563      *
 564      * @return the {@code NumberFormat} instance for currency formatting
 565      * @see java.util.Locale#getDefault(java.util.Locale.Category)
 566      * @see java.util.Locale.Category#FORMAT
 567      */
 568     public static final NumberFormat getCurrencyInstance() {
 569         return getInstance(Locale.getDefault(Locale.Category.FORMAT), CURRENCYSTYLE);
 570     }
 571 
 572     /**
 573      * Returns a currency format for the specified locale.
 574      *
 575      * @param inLocale the desired locale
 576      * @return the {@code NumberFormat} instance for currency formatting
 577      */
 578     public static NumberFormat getCurrencyInstance(Locale inLocale) {
 579         return getInstance(inLocale, CURRENCYSTYLE);
 580     }
 581 
 582     /**
 583      * Returns a percentage format for the current default
 584      * {@link java.util.Locale.Category#FORMAT FORMAT} locale.
 585      * <p>This is equivalent to calling
 586      * {@link #getPercentInstance(Locale)
 587      *     getPercentInstance(Locale.getDefault(Locale.Category.FORMAT))}.
 588      *
 589      * @return the {@code NumberFormat} instance for percentage formatting
 590      * @see java.util.Locale#getDefault(java.util.Locale.Category)
 591      * @see java.util.Locale.Category#FORMAT
 592      */
 593     public static final NumberFormat getPercentInstance() {
 594         return getInstance(Locale.getDefault(Locale.Category.FORMAT), PERCENTSTYLE);
 595     }
 596 
 597     /**
 598      * Returns a percentage format for the specified locale.
 599      *
 600      * @param inLocale the desired locale
 601      * @return the {@code NumberFormat} instance for percentage formatting
 602      */
 603     public static NumberFormat getPercentInstance(Locale inLocale) {
 604         return getInstance(inLocale, PERCENTSTYLE);
 605     }
 606 
 607     /**
 608      * Returns a scientific format for the current default locale.
 609      */
 610     /*public*/ final static NumberFormat getScientificInstance() {
 611         return getInstance(Locale.getDefault(Locale.Category.FORMAT), SCIENTIFICSTYLE);
 612     }
 613 
 614     /**
 615      * Returns a scientific format for the specified locale.
 616      *
 617      * @param inLocale the desired locale
 618      */
 619     /*public*/ static NumberFormat getScientificInstance(Locale inLocale) {
 620         return getInstance(inLocale, SCIENTIFICSTYLE);











































 621     }
 622 
 623     /**
 624      * Returns an array of all locales for which the
 625      * <code>get*Instance</code> methods of this class can return
 626      * localized instances.
 627      * The returned array represents the union of locales supported by the Java
 628      * runtime and by installed
 629      * {@link java.text.spi.NumberFormatProvider NumberFormatProvider} implementations.
 630      * It must contain at least a <code>Locale</code> instance equal to
 631      * {@link java.util.Locale#US Locale.US}.
 632      *
 633      * @return An array of locales for which localized
 634      *         <code>NumberFormat</code> instances are available.
 635      */
 636     public static Locale[] getAvailableLocales() {
 637         LocaleServiceProviderPool pool =
 638             LocaleServiceProviderPool.getPool(NumberFormatProvider.class);
 639         return pool.getAvailableLocales();
 640     }


 883      * Sets the {@link java.math.RoundingMode} used in this NumberFormat.
 884      * The default implementation of this method in NumberFormat always
 885      * throws {@link java.lang.UnsupportedOperationException}.
 886      * Subclasses which handle different rounding modes should override
 887      * this method.
 888      *
 889      * @exception UnsupportedOperationException The default implementation
 890      *     always throws this exception
 891      * @exception NullPointerException if <code>roundingMode</code> is null
 892      * @param roundingMode The <code>RoundingMode</code> to be used
 893      * @see #getRoundingMode()
 894      * @since 1.6
 895      */
 896     public void setRoundingMode(RoundingMode roundingMode) {
 897         throw new UnsupportedOperationException();
 898     }
 899 
 900     // =======================privates===============================
 901 
 902     private static NumberFormat getInstance(Locale desiredLocale,
 903                                            int choice) {
 904         LocaleProviderAdapter adapter;
 905         adapter = LocaleProviderAdapter.getAdapter(NumberFormatProvider.class,
 906                                                    desiredLocale);
 907         NumberFormat numberFormat = getInstance(adapter, desiredLocale, choice);

 908         if (numberFormat == null) {
 909             numberFormat = getInstance(LocaleProviderAdapter.forJRE(),
 910                                        desiredLocale, choice);
 911         }
 912         return numberFormat;
 913     }
 914 
 915     private static NumberFormat getInstance(LocaleProviderAdapter adapter,
 916                                             Locale locale, int choice) {

 917         NumberFormatProvider provider = adapter.getNumberFormatProvider();
 918         NumberFormat numberFormat = null;
 919         switch (choice) {
 920         case NUMBERSTYLE:
 921             numberFormat = provider.getNumberInstance(locale);
 922             break;
 923         case PERCENTSTYLE:
 924             numberFormat = provider.getPercentInstance(locale);
 925             break;
 926         case CURRENCYSTYLE:
 927             numberFormat = provider.getCurrencyInstance(locale);
 928             break;
 929         case INTEGERSTYLE:
 930             numberFormat = provider.getIntegerInstance(locale);
 931             break;



 932         }
 933         return numberFormat;
 934     }
 935 
 936     /**
 937      * First, read in the default serializable data.
 938      *
 939      * Then, if <code>serialVersionOnStream</code> is less than 1, indicating that
 940      * the stream was written by JDK 1.1,
 941      * set the <code>int</code> fields such as <code>maximumIntegerDigits</code>
 942      * to be equal to the <code>byte</code> fields such as <code>maxIntegerDigits</code>,
 943      * since the <code>int</code> fields were not present in JDK 1.1.
 944      * Finally, set serialVersionOnStream back to the maximum allowed value so that
 945      * default serialization will work properly if this object is streamed out again.
 946      *
 947      * <p>If <code>minimumIntegerDigits</code> is greater than
 948      * <code>maximumIntegerDigits</code> or <code>minimumFractionDigits</code>
 949      * is greater than <code>maximumFractionDigits</code>, then the stream data
 950      * is invalid and this method throws an <code>InvalidObjectException</code>.
 951      * In addition, if any of these values is negative, then this method throws


 984     private void writeObject(ObjectOutputStream stream)
 985          throws IOException
 986     {
 987         maxIntegerDigits = (maximumIntegerDigits > Byte.MAX_VALUE) ?
 988                            Byte.MAX_VALUE : (byte)maximumIntegerDigits;
 989         minIntegerDigits = (minimumIntegerDigits > Byte.MAX_VALUE) ?
 990                            Byte.MAX_VALUE : (byte)minimumIntegerDigits;
 991         maxFractionDigits = (maximumFractionDigits > Byte.MAX_VALUE) ?
 992                             Byte.MAX_VALUE : (byte)maximumFractionDigits;
 993         minFractionDigits = (minimumFractionDigits > Byte.MAX_VALUE) ?
 994                             Byte.MAX_VALUE : (byte)minimumFractionDigits;
 995         stream.defaultWriteObject();
 996     }
 997 
 998     // Constants used by factory methods to specify a style of format.
 999     private static final int NUMBERSTYLE = 0;
1000     private static final int CURRENCYSTYLE = 1;
1001     private static final int PERCENTSTYLE = 2;
1002     private static final int SCIENTIFICSTYLE = 3;
1003     private static final int INTEGERSTYLE = 4;

1004 
1005     /**
1006      * True if the grouping (i.e. thousands) separator is used when
1007      * formatting and parsing numbers.
1008      *
1009      * @serial
1010      * @see #isGroupingUsed
1011      */
1012     private boolean groupingUsed = true;
1013 
1014     /**
1015      * The maximum number of digits allowed in the integer portion of a
1016      * number.  <code>maxIntegerDigits</code> must be greater than or equal to
1017      * <code>minIntegerDigits</code>.
1018      * <p>
1019      * <strong>Note:</strong> This field exists only for serialization
1020      * compatibility with JDK 1.1.  In Java platform 2 v1.2 and higher, the new
1021      * <code>int</code> field <code>maximumIntegerDigits</code> is used instead.
1022      * When writing to a stream, <code>maxIntegerDigits</code> is set to
1023      * <code>maximumIntegerDigits</code> or <code>Byte.MAX_VALUE</code>,


1259 
1260         /**
1261          * Constant identifying the percent field.
1262          */
1263         public static final Field PERCENT = new Field("percent");
1264 
1265         /**
1266          * Constant identifying the permille field.
1267          */
1268         public static final Field PERMILLE = new Field("per mille");
1269 
1270         /**
1271          * Constant identifying the currency field.
1272          */
1273         public static final Field CURRENCY = new Field("currency");
1274 
1275         /**
1276          * Constant identifying the exponent sign field.
1277          */
1278         public static final Field EXPONENT_SIGN = new Field("exponent sign");






































1279     }
1280 }
   1 /*
   2  * Copyright (c) 1996, 2018, 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


  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.Locale;
  51 import java.util.Map;
  52 import java.util.Objects;
  53 import java.util.concurrent.atomic.AtomicInteger;
  54 import java.util.concurrent.atomic.AtomicLong;

  55 import sun.util.locale.provider.LocaleProviderAdapter;
  56 import sun.util.locale.provider.LocaleServiceProviderPool;
  57 
  58 /**
  59  * <code>NumberFormat</code> is the abstract base class for all number
  60  * formats. This class provides the interface for formatting and parsing
  61  * numbers. <code>NumberFormat</code> also provides methods for determining
  62  * which locales have number formats, and what their names are.
  63  *
  64  * <p>
  65  * <code>NumberFormat</code> helps you to format and parse numbers for any locale.
  66  * Your code can be completely independent of the locale conventions for
  67  * decimal points, thousands-separators, or even the particular decimal
  68  * digits used, or whether the number format is even decimal.
  69  *
  70  * <p>
  71  * To format a number for the current Locale, use one of the factory
  72  * class methods:
  73  * <blockquote>
  74  * <pre>{@code


  93  * <pre>{@code
  94  * NumberFormat nf = NumberFormat.getInstance(Locale.FRENCH);
  95  * }</pre>
  96  * </blockquote>
  97  *
  98  * <p>If the locale contains "nu" (numbers) and/or "rg" (region override)
  99  * <a href="../util/Locale.html#def_locale_extension">Unicode extensions</a>,
 100  * the decimal digits, and/or the country used for formatting are overridden.
 101  * If both "nu" and "rg" are specified, the decimal digits from the "nu"
 102  * extension supersedes the implicit one from the "rg" extension.
 103  *
 104  * <p>You can also use a {@code NumberFormat} to parse numbers:
 105  * <blockquote>
 106  * <pre>{@code
 107  * myNumber = nf.parse(myString);
 108  * }</pre>
 109  * </blockquote>
 110  * Use <code>getInstance</code> or <code>getNumberInstance</code> to get the
 111  * normal number format. Use <code>getIntegerInstance</code> to get an
 112  * integer number format. Use <code>getCurrencyInstance</code> to get the
 113  * currency number format. Use {@code getCompactNumberInstance} to get the
 114  * compact number format to format a number in shorter form. For example,
 115  * {@code 2000} can be formatted as {@code "2K"} in
 116  * {@link java.util.Locale#US US locale}. Use <code>getPercentInstance</code>
 117  * to get a format for displaying percentages. With this format, a fraction
 118  * like 0.53 is displayed as 53%.
 119  *
 120  * <p>
 121  * You can also control the display of numbers with such methods as
 122  * <code>setMinimumFractionDigits</code>.
 123  * If you want even more control over the format or parsing,
 124  * or want to give your users more control,
 125  * you can try casting the <code>NumberFormat</code> you get from the factory methods
 126  * to a {@code DecimalFormat} or {@code CompactNumberFormat} depending on
 127  * the factory method used. This will work for the vast majority of locales;
 128  * just remember to put it in a <code>try</code> block in case you encounter
 129  * an unusual one.
 130  *
 131  * <p>
 132  * NumberFormat and DecimalFormat are designed such that some controls
 133  * work for formatting and others work for parsing.  The following is
 134  * the detailed description for each these control methods,
 135  * <p>
 136  * setParseIntegerOnly : only affects parsing, e.g.
 137  * if true,  "3456.78" &rarr; 3456 (and leaves the parse position just after index 6)
 138  * if false, "3456.78" &rarr; 3456.78 (and leaves the parse position just after index 8)
 139  * This is independent of formatting.  If you want to not show a decimal point
 140  * where there might be no digits after the decimal point, use
 141  * setDecimalSeparatorAlwaysShown.
 142  * <p>
 143  * setDecimalSeparatorAlwaysShown : only affects formatting, and only where
 144  * there might be no digits after the decimal point, such as with a pattern
 145  * like "#,##0.##", e.g.,
 146  * if true,  3456.00 &rarr; "3,456."
 147  * if false, 3456.00 &rarr; "3456"
 148  * This is independent of parsing.  If you want parsing to stop at the decimal
 149  * point, use setParseIntegerOnly.


 186  * @implSpec The {@link #format(double, StringBuffer, FieldPosition)},
 187  * {@link #format(long, StringBuffer, FieldPosition)} and
 188  * {@link #parse(String, ParsePosition)} methods may throw
 189  * {@code NullPointerException}, if any of their parameter is {@code null}.
 190  * The subclass may provide its own implementation and specification about
 191  * {@code NullPointerException}.
 192  *
 193  * <p>
 194  * The default implementation provides rounding modes defined
 195  * in {@link java.math.RoundingMode} for formatting numbers. It
 196  * uses the {@linkplain java.math.RoundingMode#HALF_EVEN
 197  * round half-even algorithm}. To change the rounding mode use
 198  * {@link #setRoundingMode(java.math.RoundingMode) setRoundingMode}.
 199  * The {@code NumberFormat} returned by the static factory methods is
 200  * configured to round floating point numbers using half-even
 201  * rounding (see {@link java.math.RoundingMode#HALF_EVEN
 202  * RoundingMode.HALF_EVEN}) for formatting.
 203  *
 204  * @see          DecimalFormat
 205  * @see          ChoiceFormat
 206  * @see          CompactNumberFormat
 207  * @author       Mark Davis
 208  * @author       Helena Shih
 209  * @since 1.1
 210  */
 211 public abstract class NumberFormat extends Format  {
 212 
 213     /**
 214      * Field constant used to construct a FieldPosition object. Signifies that
 215      * the position of the integer part of a formatted number should be returned.
 216      * @see java.text.FieldPosition
 217      */
 218     public static final int INTEGER_FIELD = 0;
 219 
 220     /**
 221      * Field constant used to construct a FieldPosition object. Signifies that
 222      * the position of the fraction part of a formatted number should be returned.
 223      * @see java.text.FieldPosition
 224      */
 225     public static final int FRACTION_FIELD = 1;
 226 


 458      * @param value {@code true} if numbers should be parsed as integers only;
 459      *              {@code false} otherwise
 460      * @see #isParseIntegerOnly
 461      */
 462     public void setParseIntegerOnly(boolean value) {
 463         parseIntegerOnly = value;
 464     }
 465 
 466     //============== Locale Stuff =====================
 467 
 468     /**
 469      * Returns a general-purpose number format for the current default
 470      * {@link java.util.Locale.Category#FORMAT FORMAT} locale.
 471      * This is the same as calling
 472      * {@link #getNumberInstance() getNumberInstance()}.
 473      *
 474      * @return the {@code NumberFormat} instance for general-purpose number
 475      * formatting
 476      */
 477     public static final NumberFormat getInstance() {
 478         return getInstance(Locale.getDefault(Locale.Category.FORMAT), null, NUMBERSTYLE);
 479     }
 480 
 481     /**
 482      * Returns a general-purpose number format for the specified locale.
 483      * This is the same as calling
 484      * {@link #getNumberInstance(java.util.Locale) getNumberInstance(inLocale)}.
 485      *
 486      * @param inLocale the desired locale
 487      * @return the {@code NumberFormat} instance for general-purpose number
 488      * formatting
 489      */
 490     public static NumberFormat getInstance(Locale inLocale) {
 491         return getInstance(inLocale, null, NUMBERSTYLE);
 492     }
 493 
 494     /**
 495      * Returns a general-purpose number format for the current default
 496      * {@link java.util.Locale.Category#FORMAT FORMAT} locale.
 497      * <p>This is equivalent to calling
 498      * {@link #getNumberInstance(Locale)
 499      *     getNumberInstance(Locale.getDefault(Locale.Category.FORMAT))}.
 500      *
 501      * @return the {@code NumberFormat} instance for general-purpose number
 502      * formatting
 503      * @see java.util.Locale#getDefault(java.util.Locale.Category)
 504      * @see java.util.Locale.Category#FORMAT
 505      */
 506     public static final NumberFormat getNumberInstance() {
 507         return getInstance(Locale.getDefault(Locale.Category.FORMAT), null, NUMBERSTYLE);
 508     }
 509 
 510     /**
 511      * Returns a general-purpose number format for the specified locale.
 512      *
 513      * @param inLocale the desired locale
 514      * @return the {@code NumberFormat} instance for general-purpose number
 515      * formatting
 516      */
 517     public static NumberFormat getNumberInstance(Locale inLocale) {
 518         return getInstance(inLocale, null, NUMBERSTYLE);
 519     }
 520 
 521     /**
 522      * Returns an integer number format for the current default
 523      * {@link java.util.Locale.Category#FORMAT FORMAT} locale. The
 524      * returned number format is configured to round floating point numbers
 525      * to the nearest integer using half-even rounding (see {@link
 526      * java.math.RoundingMode#HALF_EVEN RoundingMode.HALF_EVEN}) for formatting,
 527      * and to parse only the integer part of an input string (see {@link
 528      * #isParseIntegerOnly isParseIntegerOnly}).
 529      * <p>This is equivalent to calling
 530      * {@link #getIntegerInstance(Locale)
 531      *     getIntegerInstance(Locale.getDefault(Locale.Category.FORMAT))}.
 532      *
 533      * @see #getRoundingMode()
 534      * @see java.util.Locale#getDefault(java.util.Locale.Category)
 535      * @see java.util.Locale.Category#FORMAT
 536      * @return a number format for integer values
 537      * @since 1.4
 538      */
 539     public static final NumberFormat getIntegerInstance() {
 540         return getInstance(Locale.getDefault(Locale.Category.FORMAT), null, INTEGERSTYLE);
 541     }
 542 
 543     /**
 544      * Returns an integer number format for the specified locale. The
 545      * returned number format is configured to round floating point numbers
 546      * to the nearest integer using half-even rounding (see {@link
 547      * java.math.RoundingMode#HALF_EVEN RoundingMode.HALF_EVEN}) for formatting,
 548      * and to parse only the integer part of an input string (see {@link
 549      * #isParseIntegerOnly isParseIntegerOnly}).
 550      *
 551      * @param inLocale the desired locale
 552      * @see #getRoundingMode()
 553      * @return a number format for integer values
 554      * @since 1.4
 555      */
 556     public static NumberFormat getIntegerInstance(Locale inLocale) {
 557         return getInstance(inLocale, null, INTEGERSTYLE);
 558     }
 559 
 560     /**
 561      * Returns a currency format for the current default
 562      * {@link java.util.Locale.Category#FORMAT FORMAT} locale.
 563      * <p>This is equivalent to calling
 564      * {@link #getCurrencyInstance(Locale)
 565      *     getCurrencyInstance(Locale.getDefault(Locale.Category.FORMAT))}.
 566      *
 567      * @return the {@code NumberFormat} instance for currency formatting
 568      * @see java.util.Locale#getDefault(java.util.Locale.Category)
 569      * @see java.util.Locale.Category#FORMAT
 570      */
 571     public static final NumberFormat getCurrencyInstance() {
 572         return getInstance(Locale.getDefault(Locale.Category.FORMAT), null, CURRENCYSTYLE);
 573     }
 574 
 575     /**
 576      * Returns a currency format for the specified locale.
 577      *
 578      * @param inLocale the desired locale
 579      * @return the {@code NumberFormat} instance for currency formatting
 580      */
 581     public static NumberFormat getCurrencyInstance(Locale inLocale) {
 582         return getInstance(inLocale, null, CURRENCYSTYLE);
 583     }
 584 
 585     /**
 586      * Returns a percentage format for the current default
 587      * {@link java.util.Locale.Category#FORMAT FORMAT} locale.
 588      * <p>This is equivalent to calling
 589      * {@link #getPercentInstance(Locale)
 590      *     getPercentInstance(Locale.getDefault(Locale.Category.FORMAT))}.
 591      *
 592      * @return the {@code NumberFormat} instance for percentage formatting
 593      * @see java.util.Locale#getDefault(java.util.Locale.Category)
 594      * @see java.util.Locale.Category#FORMAT
 595      */
 596     public static final NumberFormat getPercentInstance() {
 597         return getInstance(Locale.getDefault(Locale.Category.FORMAT), null, PERCENTSTYLE);
 598     }
 599 
 600     /**
 601      * Returns a percentage format for the specified locale.
 602      *
 603      * @param inLocale the desired locale
 604      * @return the {@code NumberFormat} instance for percentage formatting
 605      */
 606     public static NumberFormat getPercentInstance(Locale inLocale) {
 607         return getInstance(inLocale, null, PERCENTSTYLE);
 608     }
 609 
 610     /**
 611      * Returns a scientific format for the current default locale.
 612      */
 613     /*public*/ final static NumberFormat getScientificInstance() {
 614         return getInstance(Locale.getDefault(Locale.Category.FORMAT), null, SCIENTIFICSTYLE);
 615     }
 616 
 617     /**
 618      * Returns a scientific format for the specified locale.
 619      *
 620      * @param inLocale the desired locale
 621      */
 622     /*public*/ static NumberFormat getScientificInstance(Locale inLocale) {
 623         return getInstance(inLocale, null, SCIENTIFICSTYLE);
 624     }
 625     
 626     /**
 627      * Returns a compact number format for the default
 628      * {@link java.util.Locale.Category#FORMAT FORMAT} locale with
 629      * {@link NumberFormat.Style#SHORT "SHORT"} format style.
 630      *
 631      * @return A {@code NumberFormat} instance for compact number
 632      *         formatting
 633      * 
 634      * @see CompactNumberFormat
 635      * @see NumberFormat.Style
 636      * @see java.util.Locale#getDefault(java.util.Locale.Category)
 637      * @see java.util.Locale.Category#FORMAT
 638      * @since 12
 639      */
 640     public static NumberFormat getCompactNumberInstance() {
 641         return getInstance(Locale.getDefault(
 642                 Locale.Category.FORMAT), NumberFormat.Style.SHORT, COMPACTSTYLE);
 643     }
 644 
 645     /**
 646      * Returns a compact number format for the specified {@link java.util.Locale locale}
 647      * and {@link NumberFormat.Style formatStyle}.
 648      *
 649      * @param locale the desired locale
 650      * @param formatStyle the style for formatting a number
 651      * @return A {@code NumberFormat} instance for compact number
 652      *         formatting
 653      * @throws NullPointerException if {@code locale} or {@code formatStyle}
 654      *                              is {@code null}
 655      *
 656      * @see CompactNumberFormat
 657      * @see NumberFormat.Style
 658      * @see java.util.Locale
 659      * @since 12
 660      */
 661     public static NumberFormat getCompactNumberInstance(Locale locale,
 662             NumberFormat.Style formatStyle) {
 663 
 664         Objects.requireNonNull(locale);
 665         Objects.requireNonNull(formatStyle);
 666         return getInstance(locale, formatStyle, COMPACTSTYLE);
 667     }
 668 
 669     /**
 670      * Returns an array of all locales for which the
 671      * <code>get*Instance</code> methods of this class can return
 672      * localized instances.
 673      * The returned array represents the union of locales supported by the Java
 674      * runtime and by installed
 675      * {@link java.text.spi.NumberFormatProvider NumberFormatProvider} implementations.
 676      * It must contain at least a <code>Locale</code> instance equal to
 677      * {@link java.util.Locale#US Locale.US}.
 678      *
 679      * @return An array of locales for which localized
 680      *         <code>NumberFormat</code> instances are available.
 681      */
 682     public static Locale[] getAvailableLocales() {
 683         LocaleServiceProviderPool pool =
 684             LocaleServiceProviderPool.getPool(NumberFormatProvider.class);
 685         return pool.getAvailableLocales();
 686     }


 929      * Sets the {@link java.math.RoundingMode} used in this NumberFormat.
 930      * The default implementation of this method in NumberFormat always
 931      * throws {@link java.lang.UnsupportedOperationException}.
 932      * Subclasses which handle different rounding modes should override
 933      * this method.
 934      *
 935      * @exception UnsupportedOperationException The default implementation
 936      *     always throws this exception
 937      * @exception NullPointerException if <code>roundingMode</code> is null
 938      * @param roundingMode The <code>RoundingMode</code> to be used
 939      * @see #getRoundingMode()
 940      * @since 1.6
 941      */
 942     public void setRoundingMode(RoundingMode roundingMode) {
 943         throw new UnsupportedOperationException();
 944     }
 945 
 946     // =======================privates===============================
 947 
 948     private static NumberFormat getInstance(Locale desiredLocale,
 949                                             Style formatStyle, int choice) {
 950         LocaleProviderAdapter adapter;
 951         adapter = LocaleProviderAdapter.getAdapter(NumberFormatProvider.class,
 952                 desiredLocale);
 953         NumberFormat numberFormat = getInstance(adapter, desiredLocale,
 954                 formatStyle, choice);
 955         if (numberFormat == null) {
 956             numberFormat = getInstance(LocaleProviderAdapter.forJRE(),
 957                     desiredLocale, formatStyle, choice);
 958         }
 959         return numberFormat;
 960     }
 961 
 962     private static NumberFormat getInstance(LocaleProviderAdapter adapter,
 963                                             Locale locale, Style formatStyle,
 964                                             int choice) {
 965         NumberFormatProvider provider = adapter.getNumberFormatProvider();
 966         NumberFormat numberFormat = null;
 967         switch (choice) {
 968         case NUMBERSTYLE:
 969             numberFormat = provider.getNumberInstance(locale);
 970             break;
 971         case PERCENTSTYLE:
 972             numberFormat = provider.getPercentInstance(locale);
 973             break;
 974         case CURRENCYSTYLE:
 975             numberFormat = provider.getCurrencyInstance(locale);
 976             break;
 977         case INTEGERSTYLE:
 978             numberFormat = provider.getIntegerInstance(locale);
 979             break;
 980         case COMPACTSTYLE:
 981             numberFormat = provider.getCompactNumberInstance(locale, formatStyle);
 982             break;
 983         }
 984         return numberFormat;
 985     }
 986 
 987     /**
 988      * First, read in the default serializable data.
 989      *
 990      * Then, if <code>serialVersionOnStream</code> is less than 1, indicating that
 991      * the stream was written by JDK 1.1,
 992      * set the <code>int</code> fields such as <code>maximumIntegerDigits</code>
 993      * to be equal to the <code>byte</code> fields such as <code>maxIntegerDigits</code>,
 994      * since the <code>int</code> fields were not present in JDK 1.1.
 995      * Finally, set serialVersionOnStream back to the maximum allowed value so that
 996      * default serialization will work properly if this object is streamed out again.
 997      *
 998      * <p>If <code>minimumIntegerDigits</code> is greater than
 999      * <code>maximumIntegerDigits</code> or <code>minimumFractionDigits</code>
1000      * is greater than <code>maximumFractionDigits</code>, then the stream data
1001      * is invalid and this method throws an <code>InvalidObjectException</code>.
1002      * In addition, if any of these values is negative, then this method throws


1035     private void writeObject(ObjectOutputStream stream)
1036          throws IOException
1037     {
1038         maxIntegerDigits = (maximumIntegerDigits > Byte.MAX_VALUE) ?
1039                            Byte.MAX_VALUE : (byte)maximumIntegerDigits;
1040         minIntegerDigits = (minimumIntegerDigits > Byte.MAX_VALUE) ?
1041                            Byte.MAX_VALUE : (byte)minimumIntegerDigits;
1042         maxFractionDigits = (maximumFractionDigits > Byte.MAX_VALUE) ?
1043                             Byte.MAX_VALUE : (byte)maximumFractionDigits;
1044         minFractionDigits = (minimumFractionDigits > Byte.MAX_VALUE) ?
1045                             Byte.MAX_VALUE : (byte)minimumFractionDigits;
1046         stream.defaultWriteObject();
1047     }
1048 
1049     // Constants used by factory methods to specify a style of format.
1050     private static final int NUMBERSTYLE = 0;
1051     private static final int CURRENCYSTYLE = 1;
1052     private static final int PERCENTSTYLE = 2;
1053     private static final int SCIENTIFICSTYLE = 3;
1054     private static final int INTEGERSTYLE = 4;
1055     private static final int COMPACTSTYLE = 5;
1056 
1057     /**
1058      * True if the grouping (i.e. thousands) separator is used when
1059      * formatting and parsing numbers.
1060      *
1061      * @serial
1062      * @see #isGroupingUsed
1063      */
1064     private boolean groupingUsed = true;
1065 
1066     /**
1067      * The maximum number of digits allowed in the integer portion of a
1068      * number.  <code>maxIntegerDigits</code> must be greater than or equal to
1069      * <code>minIntegerDigits</code>.
1070      * <p>
1071      * <strong>Note:</strong> This field exists only for serialization
1072      * compatibility with JDK 1.1.  In Java platform 2 v1.2 and higher, the new
1073      * <code>int</code> field <code>maximumIntegerDigits</code> is used instead.
1074      * When writing to a stream, <code>maxIntegerDigits</code> is set to
1075      * <code>maximumIntegerDigits</code> or <code>Byte.MAX_VALUE</code>,


1311 
1312         /**
1313          * Constant identifying the percent field.
1314          */
1315         public static final Field PERCENT = new Field("percent");
1316 
1317         /**
1318          * Constant identifying the permille field.
1319          */
1320         public static final Field PERMILLE = new Field("per mille");
1321 
1322         /**
1323          * Constant identifying the currency field.
1324          */
1325         public static final Field CURRENCY = new Field("currency");
1326 
1327         /**
1328          * Constant identifying the exponent sign field.
1329          */
1330         public static final Field EXPONENT_SIGN = new Field("exponent sign");
1331 
1332         /**
1333          * Constant identifying the prefix field.
1334          *
1335          * @since 12
1336          */
1337         public static final Field PREFIX = new Field("prefix");
1338 
1339         /**
1340          * Constant identifying the suffix field.
1341          *
1342          * @since 12
1343          */
1344         public static final Field SUFFIX = new Field("suffix");
1345     }
1346 
1347     /**
1348      * A number format style.
1349      * <p>
1350      * {@code Style} is an enum which represents the style for formatting
1351      * a number within a given {@code NumberFormat} instance.
1352      *
1353      * @see CompactNumberFormat
1354      * @see NumberFormat#getCompactNumberInstance(Locale, Style)
1355      * @since 12
1356      */
1357     public enum Style {
1358         
1359         /**
1360          * The {@code SHORT} number format style.
1361          */
1362         SHORT,
1363 
1364         /**
1365          * The {@code LONG} number format style.
1366          */
1367         LONG
1368 
1369     }
1370 }
< prev index next >