2 *******************************************************************************
3 * Copyright (C) 1996-2011, International Business Machines Corporation and *
4 * others. All Rights Reserved. *
5 *******************************************************************************
8 package com.ibm.icu.text;
10 import java.io.IOException;
11 import java.io.InvalidObjectException;
12 import java.io.ObjectInputStream;
13 import java.io.ObjectOutputStream;
14 import java.math.BigInteger;
15 import java.text.FieldPosition;
16 import java.text.Format;
17 import java.text.ParseException;
18 import java.text.ParsePosition;
19 import java.util.Collections;
20 import java.util.Locale;
21 import java.util.MissingResourceException;
24 import com.ibm.icu.impl.ICUResourceBundle;
25 import com.ibm.icu.util.Currency;
26 import com.ibm.icu.util.CurrencyAmount;
27 import com.ibm.icu.util.ULocale;
28 import com.ibm.icu.util.ULocale.Category;
29 import com.ibm.icu.util.UResourceBundle;
32 * {@icuenhanced java.text.NumberFormat}.{@icu _usage_}
34 * <code>NumberFormat</code> is the abstract base class for all number
35 * formats. This class provides the interface for formatting and parsing
36 * numbers. <code>NumberFormat</code> also provides methods for determining
37 * which locales have number formats, and what their names are.
39 * <code>NumberFormat</code> helps you to format and parse numbers for any locale.
40 * Your code can be completely independent of the locale conventions for
41 * decimal points, thousands-separators, or even the particular decimal
42 * digits used, or whether the number format is even decimal.
45 * To format a number for the current Locale, use one of the factory
49 * myString = NumberFormat.getInstance().format(myNumber);
52 * If you are formatting multiple numbers, it is
53 * more efficient to get the format and use it multiple times so that
54 * the system doesn't have to fetch the information about the local
55 * language and country conventions multiple times.
58 * NumberFormat nf = NumberFormat.getInstance();
59 * for (int i = 0; i < a.length; ++i) {
60 * output.println(nf.format(myNumber[i]) + "; ");
64 * To format a number for a different Locale, specify it in the
65 * call to <code>getInstance</code>.
68 * NumberFormat nf = NumberFormat.getInstance(Locale.FRENCH);
71 * You can also use a <code>NumberFormat</code> to parse numbers:
74 * myNumber = nf.parse(myString);
77 * Use <code>getInstance</code> or <code>getNumberInstance</code> to get the
78 * normal number format. Use <code>getIntegerInstance</code> to get an
79 * integer number format. Use <code>getCurrencyInstance</code> to get the
80 * currency number format. And use <code>getPercentInstance</code> to get a
81 * format for displaying percentages. With this format, a fraction like
82 * 0.53 is displayed as 53%.
85 * Starting from ICU 4.2, you can use getInstance() by passing in a 'style'
86 * as parameter to get the correct instance.
88 * use getInstance(...NUMBERSTYLE) to get the normal number format,
89 * getInstance(...PERCENTSTYLE) to get a format for displaying percentage,
90 * getInstance(...SCIENTIFICSTYLE) to get a format for displaying scientific number,
91 * getInstance(...INTEGERSTYLE) to get an integer number format,
92 * getInstance(...CURRENCYSTYLE) to get the currency number format,
93 * in which the currency is represented by its symbol, for example, "$3.00".
94 * getInstance(...ISOCURRENCYSTYLE) to get the currency number format,
95 * in which the currency is represented by its ISO code, for example "USD3.00".
96 * getInstance(...PLURALCURRENCYSTYLE) to get the currency number format,
97 * in which the currency is represented by its full name in plural format,
98 * for example, "3.00 US dollars" or "1.00 US dollar".
102 * You can also control the display of numbers with such methods as
103 * <code>setMinimumFractionDigits</code>.
104 * If you want even more control over the format or parsing,
105 * or want to give your users more control,
106 * you can try casting the <code>NumberFormat</code> you get from the factory methods
107 * to a <code>DecimalFormat</code>. This will work for the vast majority
108 * of locales; just remember to put it in a <code>try</code> block in case you
109 * encounter an unusual one.
112 * NumberFormat is designed such that some controls
113 * work for formatting and others work for parsing. The following is
114 * the detailed description for each these control methods,
116 * setParseIntegerOnly : only affects parsing, e.g.
117 * if true, "3456.78" -> 3456 (and leaves the parse position just after '6')
118 * if false, "3456.78" -> 3456.78 (and leaves the parse position just after '8')
119 * This is independent of formatting. If you want to not show a decimal point
120 * where there might be no digits after the decimal point, use
121 * setDecimalSeparatorAlwaysShown on DecimalFormat.
123 * You can also use forms of the <code>parse</code> and <code>format</code>
124 * methods with <code>ParsePosition</code> and <code>FieldPosition</code> to
127 * <li> progressively parse through pieces of a string
128 * <li> align the decimal point and other areas
130 * For example, you can align numbers in two ways:
132 * <li> If you are using a monospaced font with spacing for alignment,
133 * you can pass the <code>FieldPosition</code> in your format call, with
134 * <code>field</code> = <code>INTEGER_FIELD</code>. On output,
135 * <code>getEndIndex</code> will be set to the offset between the
136 * last character of the integer and the decimal. Add
137 * (desiredSpaceCount - getEndIndex) spaces at the front of the string.
139 * <li> If you are using proportional fonts,
140 * instead of padding with spaces, measure the width
141 * of the string in pixels from the start to <code>getEndIndex</code>.
142 * Then move the pen by
143 * (desiredPixelWidth - widthToAlignmentPoint) before drawing the text.
144 * It also works where there is no decimal, but possibly additional
145 * characters at the end, e.g., with parentheses in negative
146 * numbers: "(12)" for -12.
149 * <h4>Synchronization</h4>
151 * Number formats are generally not synchronized. It is recommended to create
152 * separate format instances for each thread. If multiple threads access a format
153 * concurrently, it must be synchronized externally.
156 * <h4>DecimalFormat</h4>
157 * <p>DecimalFormat is the concrete implementation of NumberFormat, and the
158 * NumberFormat API is essentially an abstraction from DecimalFormat's API.
159 * Refer to DecimalFormat for more information about this API.</p>
162 * see java.text.ChoiceFormat
164 * @author Helena Shih
168 public abstract class NumberFormat extends UFormat {
171 * {@icu} Constant to specify normal number style of format.
174 public static final int NUMBERSTYLE = 0;
176 * {@icu} Constant to specify currency style of format which uses currency symbol
177 * to represent currency, for example: "$3.00".
180 public static final int CURRENCYSTYLE = 1;
182 * {@icu} Constant to specify a style of format to display percent.
185 public static final int PERCENTSTYLE = 2;
187 * {@icu} Constant to specify a style of format to display scientific number.
190 public static final int SCIENTIFICSTYLE = 3;
192 * {@icu} Constant to specify a integer number style format.
195 public static final int INTEGERSTYLE = 4;
197 * {@icu} Constant to specify currency style of format which uses currency
198 * ISO code to represent currency, for example: "USD3.00".
201 public static final int ISOCURRENCYSTYLE = 5;
203 * {@icu} Constant to specify currency style of format which uses currency
204 * long name with plural format to represent currency, for example,
208 public static final int PLURALCURRENCYSTYLE = 6;
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
216 public static final int INTEGER_FIELD = 0;
219 * Field constant used to construct a FieldPosition object. Signifies that
220 * the position of the fraction part of a formatted number should be returned.
221 * @see java.text.FieldPosition
224 public static final int FRACTION_FIELD = 1;
227 * Formats a number and appends the resulting text to the given string buffer.
228 * {@icunote} recognizes <code>BigInteger</code>
229 * and <code>BigDecimal</code> objects.
230 * @see java.text.Format#format(Object, StringBuffer, FieldPosition)
233 public StringBuffer format(Object number,
234 StringBuffer toAppendTo,
236 if (number instanceof Long) {
237 return format(((Long)number).longValue(), toAppendTo, pos);
238 } else if (number instanceof BigInteger) {
239 return format((BigInteger) number, toAppendTo, pos);
240 } else if (number instanceof java.math.BigDecimal) {
241 return format((java.math.BigDecimal) number, toAppendTo, pos);
242 } else if (number instanceof com.ibm.icu.math.BigDecimal) {
243 return format((com.ibm.icu.math.BigDecimal) number, toAppendTo, pos);
244 } else if (number instanceof CurrencyAmount) {
245 return format((CurrencyAmount)number, toAppendTo, pos);
246 } else if (number instanceof Number) {
247 return format(((Number)number).doubleValue(), toAppendTo, pos);
249 throw new IllegalArgumentException("Cannot format given Object as a Number");
254 * Parses text from a string to produce a number.
255 * @param source the String to parse
256 * @param parsePosition the position at which to start the parse
257 * @return the parsed number, or null
258 * @see java.text.NumberFormat#parseObject(String, ParsePosition)
261 public final Object parseObject(String source,
262 ParsePosition parsePosition) {
263 return parse(source, parsePosition);
267 * Specialization of format.
268 * @see java.text.Format#format(Object)
271 public final String format(double number) {
272 return format(number,new StringBuffer(),
273 new FieldPosition(0)).toString();
277 * Specialization of format.
278 * @see java.text.Format#format(Object)
281 public final String format(long number) {
282 StringBuffer buf = new StringBuffer(19);
283 FieldPosition pos = new FieldPosition(0);
284 format(number, buf, pos);
285 return buf.toString();
289 * {@icu} Convenience method to format a BigInteger.
292 public final String format(BigInteger number) {
293 return format(number, new StringBuffer(),
294 new FieldPosition(0)).toString();
298 * Convenience method to format a BigDecimal.
301 public final String format(java.math.BigDecimal number) {
302 return format(number, new StringBuffer(),
303 new FieldPosition(0)).toString();
307 * {@icu} Convenience method to format an ICU BigDecimal.
310 public final String format(com.ibm.icu.math.BigDecimal number) {
311 return format(number, new StringBuffer(),
312 new FieldPosition(0)).toString();
316 * {@icu} Convenience method to format a CurrencyAmount.
319 public final String format(CurrencyAmount currAmt) {
320 return format(currAmt, new StringBuffer(),
321 new FieldPosition(0)).toString();
325 * Specialization of format.
326 * @see java.text.Format#format(Object, StringBuffer, FieldPosition)
329 public abstract StringBuffer format(double number,
330 StringBuffer toAppendTo,
334 * Specialization of format.
335 * @see java.text.Format#format(Object, StringBuffer, FieldPosition)
338 public abstract StringBuffer format(long number,
339 StringBuffer toAppendTo,
342 * {@icu} Formats a BigInteger. Specialization of format.
343 * @see java.text.Format#format(Object, StringBuffer, FieldPosition)
346 public abstract StringBuffer format(BigInteger number,
347 StringBuffer toAppendTo,
350 * {@icu} Formats a BigDecimal. Specialization of format.
351 * @see java.text.Format#format(Object, StringBuffer, FieldPosition)
354 public abstract StringBuffer format(java.math.BigDecimal number,
355 StringBuffer toAppendTo,
358 * {@icu} Formats an ICU BigDecimal. Specialization of format.
359 * @see java.text.Format#format(Object, StringBuffer, FieldPosition)
362 public abstract StringBuffer format(com.ibm.icu.math.BigDecimal number,
363 StringBuffer toAppendTo,
366 * {@icu} Formats a CurrencyAmount. Specialization of format.
367 * @see java.text.Format#format(Object, StringBuffer, FieldPosition)
370 public StringBuffer format(CurrencyAmount currAmt,
371 StringBuffer toAppendTo,
373 // Default implementation -- subclasses may override
374 Currency save = getCurrency(), curr = currAmt.getCurrency();
375 boolean same = curr.equals(save);
376 if (!same) setCurrency(curr);
377 format(currAmt.getNumber(), toAppendTo, pos);
378 if (!same) setCurrency(save);
383 * Returns a Long if possible (e.g., within the range [Long.MIN_VALUE,
384 * Long.MAX_VALUE] and with no decimals), otherwise a Double.
385 * If IntegerOnly is set, will stop at a decimal
386 * point (or equivalent; e.g., for rational numbers "1 2/3", will stop
388 * Does not throw an exception; if no object can be parsed, index is
390 * @see #isParseIntegerOnly
391 * @see java.text.Format#parseObject(String, ParsePosition)
394 public abstract Number parse(String text, ParsePosition parsePosition);
397 * Parses text from the beginning of the given string to produce a number.
398 * The method might not use the entire text of the given string.
400 * @param text A String whose beginning should be parsed.
401 * @return A Number parsed from the string.
402 * @throws ParseException if the beginning of the specified string
407 //Bug 4375399 [Richard/GCL]
408 public Number parse(String text) throws ParseException {
409 ParsePosition parsePosition = new ParsePosition(0);
410 Number result = parse(text, parsePosition);
411 if (parsePosition.getIndex() == 0) {
412 throw new ParseException("Unparseable number: \"" + text + '"',
413 parsePosition.getErrorIndex());
419 * Parses text from the given string as a CurrencyAmount. Unlike
420 * the parse() method, this method will attempt to parse a generic
421 * currency name, searching for a match of this object's locale's
422 * currency display names, or for a 3-letter ISO currency code.
423 * This method will fail if this format is not a currency format,
424 * that is, if it does not contain the currency pattern symbol
425 * (U+00A4) in its prefix or suffix.
427 * @param text the string to parse
428 * @param pos input-output position; on input, the position within
429 * text to match; must have 0 <= pos.getIndex() < text.length();
430 * on output, the position after the last matched character. If
431 * the parse fails, the position in unchanged upon output.
432 * @return a CurrencyAmount, or null upon failure
435 public CurrencyAmount parseCurrency(String text, ParsePosition pos) {
437 // Default implementation only -- subclasses should override
438 Number n = parse(text, pos);
439 return n == null ? null : new CurrencyAmount(n, getEffectiveCurrency());
444 * Returns true if this format will parse numbers as integers only.
445 * For example in the English locale, with ParseIntegerOnly true, the
446 * string "1234." would be parsed as the integer value 1234 and parsing
447 * would stop at the "." character. The decimal separator accepted
448 * by the parse operation is locale-dependent and determined by the
450 * @return true if this will parse integers only
453 public boolean isParseIntegerOnly() {
454 return parseIntegerOnly;
458 * Sets whether or not numbers should be parsed as integers only.
459 * @param value true if this should parse integers only
460 * @see #isParseIntegerOnly
463 public void setParseIntegerOnly(boolean value) {
464 parseIntegerOnly = value;
468 * {@icu} Sets whether strict parsing is in effect. When this is true, the
469 * following conditions cause a parse failure (examples use the pattern "#,##0.#"):<ul>
470 * <li>Leading or doubled grouping separators<br>
471 * ',123' and '1,,234" fail</li>
472 * <li>Groups of incorrect length when grouping is used<br>
473 * '1,23' and '1234,567' fail, but '1234' passes</li>
474 * <li>Grouping separators used in numbers followed by exponents<br>
475 * '1,234E5' fails, but '1234E5' and '1,234E' pass ('E' is not an exponent when
476 * not followed by a number)</li>
478 * When strict parsing is off, all grouping separators are ignored.
479 * This is the default behavior.
480 * @param value True to enable strict parsing. Default is false.
481 * @see #isParseStrict
484 public void setParseStrict(boolean value) {
489 * {@icu} Returns whether strict parsing is in effect.
490 * @return true if strict parsing is in effect
491 * @see #setParseStrict
494 public boolean isParseStrict() {
498 //============== Locale Stuff =====================
501 * Returns the default number format for the current default <code>FORMAT</code> locale.
502 * The default format is one of the styles provided by the other
503 * factory methods: getNumberInstance, getIntegerInstance,
504 * getCurrencyInstance or getPercentInstance.
505 * Exactly which one is locale-dependent.
506 * @see Category#FORMAT
509 //Bug 4408066 [Richard/GCL]
510 public final static NumberFormat getInstance() {
511 return getInstance(ULocale.getDefault(Category.FORMAT), NUMBERSTYLE);
515 * Returns the default number format for the specified locale.
516 * The default format is one of the styles provided by the other
517 * factory methods: getNumberInstance, getCurrencyInstance or getPercentInstance.
518 * Exactly which one is locale-dependent.
521 public static NumberFormat getInstance(Locale inLocale) {
522 return getInstance(ULocale.forLocale(inLocale), NUMBERSTYLE);
526 * {@icu} Returns the default number format for the specified locale.
527 * The default format is one of the styles provided by the other
528 * factory methods: getNumberInstance, getCurrencyInstance or getPercentInstance.
529 * Exactly which one is locale-dependent.
532 public static NumberFormat getInstance(ULocale inLocale) {
533 return getInstance(inLocale, NUMBERSTYLE);
537 * {@icu} Returns a specific style number format for default <code>FORMAT</code> locale.
538 * @param style number format style
539 * @see Category#FORMAT
542 public final static NumberFormat getInstance(int style) {
543 return getInstance(ULocale.getDefault(Category.FORMAT), style);
547 * {@icu} Returns a specific style number format for a specific locale.
548 * @param inLocale the specific locale.
549 * @param style number format style
552 public static NumberFormat getInstance(Locale inLocale, int style) {
553 return getInstance(ULocale.forLocale(inLocale), style);
558 * Returns a general-purpose number format for the current default <code>FORMAT</code> locale.
559 * @see Category#FORMAT
562 public final static NumberFormat getNumberInstance() {
563 return getInstance(ULocale.getDefault(Category.FORMAT), NUMBERSTYLE);
567 * Returns a general-purpose number format for the specified locale.
570 public static NumberFormat getNumberInstance(Locale inLocale) {
571 return getInstance(ULocale.forLocale(inLocale), NUMBERSTYLE);
575 * {@icu} Returns a general-purpose number format for the specified locale.
578 public static NumberFormat getNumberInstance(ULocale inLocale) {
579 return getInstance(inLocale, NUMBERSTYLE);
583 * Returns an integer number format for the current default <code>FORMAT</code> locale. The
584 * returned number format is configured to round floating point numbers
585 * to the nearest integer using IEEE half-even rounding (see {@link
586 * com.ibm.icu.math.BigDecimal#ROUND_HALF_EVEN ROUND_HALF_EVEN}) for formatting,
587 * and to parse only the integer part of an input string (see {@link
588 * #isParseIntegerOnly isParseIntegerOnly}).
590 * @return a number format for integer values
591 * @see Category#FORMAT
594 //Bug 4408066 [Richard/GCL]
595 public final static NumberFormat getIntegerInstance() {
596 return getInstance(ULocale.getDefault(Category.FORMAT), INTEGERSTYLE);
600 * Returns an integer number format for the specified locale. The
601 * returned number format is configured to round floating point numbers
602 * to the nearest integer using IEEE half-even rounding (see {@link
603 * com.ibm.icu.math.BigDecimal#ROUND_HALF_EVEN ROUND_HALF_EVEN}) for formatting,
604 * and to parse only the integer part of an input string (see {@link
605 * #isParseIntegerOnly isParseIntegerOnly}).
607 * @param inLocale the locale for which a number format is needed
608 * @return a number format for integer values
611 //Bug 4408066 [Richard/GCL]
612 public static NumberFormat getIntegerInstance(Locale inLocale) {
613 return getInstance(ULocale.forLocale(inLocale), INTEGERSTYLE);
617 * {@icu} Returns an integer number format for the specified locale. The
618 * returned number format is configured to round floating point numbers
619 * to the nearest integer using IEEE half-even rounding (see {@link
620 * com.ibm.icu.math.BigDecimal#ROUND_HALF_EVEN ROUND_HALF_EVEN}) for formatting,
621 * and to parse only the integer part of an input string (see {@link
622 * #isParseIntegerOnly isParseIntegerOnly}).
624 * @param inLocale the locale for which a number format is needed
625 * @return a number format for integer values
628 public static NumberFormat getIntegerInstance(ULocale inLocale) {
629 return getInstance(inLocale, INTEGERSTYLE);
633 * Returns a currency format for the current default <code>FORMAT</code> locale.
634 * @return a number format for currency
635 * @see Category#FORMAT
638 public final static NumberFormat getCurrencyInstance() {
639 return getInstance(ULocale.getDefault(Category.FORMAT), CURRENCYSTYLE);
643 * Returns a currency format for the specified locale.
644 * @return a number format for currency
647 public static NumberFormat getCurrencyInstance(Locale inLocale) {
648 return getInstance(ULocale.forLocale(inLocale), CURRENCYSTYLE);
652 * {@icu} Returns a currency format for the specified locale.
653 * @return a number format for currency
656 public static NumberFormat getCurrencyInstance(ULocale inLocale) {
657 return getInstance(inLocale, CURRENCYSTYLE);
661 * Returns a percentage format for the current default <code>FORMAT</code> locale.
662 * @return a number format for percents
663 * @see Category#FORMAT
666 public final static NumberFormat getPercentInstance() {
667 return getInstance(ULocale.getDefault(Category.FORMAT), PERCENTSTYLE);
671 * Returns a percentage format for the specified locale.
672 * @return a number format for percents
675 public static NumberFormat getPercentInstance(Locale inLocale) {
676 return getInstance(ULocale.forLocale(inLocale), PERCENTSTYLE);
680 * {@icu} Returns a percentage format for the specified locale.
681 * @return a number format for percents
684 public static NumberFormat getPercentInstance(ULocale inLocale) {
685 return getInstance(inLocale, PERCENTSTYLE);
689 * {@icu} Returns a scientific format for the current default <code>FORMAT</code> locale.
690 * @return a scientific number format
691 * @see Category#FORMAT
694 public final static NumberFormat getScientificInstance() {
695 return getInstance(ULocale.getDefault(Category.FORMAT), SCIENTIFICSTYLE);
699 * {@icu} Returns a scientific format for the specified locale.
700 * @return a scientific number format
703 public static NumberFormat getScientificInstance(Locale inLocale) {
704 return getInstance(ULocale.forLocale(inLocale), SCIENTIFICSTYLE);
708 * {@icu} Returns a scientific format for the specified locale.
709 * @return a scientific number format
712 public static NumberFormat getScientificInstance(ULocale inLocale) {
713 return getInstance(inLocale, SCIENTIFICSTYLE);
716 // ===== Factory stuff =====
718 * A NumberFormatFactory is used to register new number formats. The factory
719 * should be able to create any of the predefined formats for each locale it
720 * supports. When registered, the locales it supports extend or override the
721 * locales already supported by ICU.
723 * <p><b>Note:</b> as of ICU4J 3.2, the default API for NumberFormatFactory uses
724 * ULocale instead of Locale. Instead of overriding createFormat(Locale, int),
725 * new implementations should override createFactory(ULocale, int). Note that
726 * one of these two methods <b>MUST</b> be overridden or else an infinite
731 public static abstract class NumberFormatFactory {
733 * Value passed to format requesting a default number format.
736 public static final int FORMAT_NUMBER = NUMBERSTYLE;
739 * Value passed to format requesting a currency format.
742 public static final int FORMAT_CURRENCY = CURRENCYSTYLE;
745 * Value passed to format requesting a percent format.
748 public static final int FORMAT_PERCENT = PERCENTSTYLE;
751 * Value passed to format requesting a scientific format.
754 public static final int FORMAT_SCIENTIFIC = SCIENTIFICSTYLE;
757 * Value passed to format requesting an integer format.
760 public static final int FORMAT_INTEGER = INTEGERSTYLE;
763 * Returns true if this factory is visible. Default is true.
764 * If not visible, the locales supported by this factory will not
765 * be listed by getAvailableLocales. This value must not change.
766 * @return true if the factory is visible.
769 public boolean visible() {
774 * Returns an immutable collection of the locale names directly
775 * supported by this factory.
776 * @return the supported locale names.
779 public abstract Set<String> getSupportedLocaleNames();
782 * Returns a number format of the appropriate type. If the locale
783 * is not supported, return null. If the locale is supported, but
784 * the type is not provided by this service, return null. Otherwise
785 * return an appropriate instance of NumberFormat.
786 * <b>Note:</b> as of ICU4J 3.2, implementations should override
787 * this method instead of createFormat(Locale, int).
788 * @param loc the locale for which to create the format
789 * @param formatType the type of format
790 * @return the NumberFormat, or null.
793 public NumberFormat createFormat(ULocale loc, int formatType) {
794 return createFormat(loc.toLocale(), formatType);
798 * Returns a number format of the appropriate type. If the locale
799 * is not supported, return null. If the locale is supported, but
800 * the type is not provided by this service, return null. Otherwise
801 * return an appropriate instance of NumberFormat.
802 * <b>Note:</b> as of ICU4J 3.2, createFormat(ULocale, int) should be
803 * overridden instead of this method. This method is no longer
804 * abstract and delegates to that method.
805 * @param loc the locale for which to create the format
806 * @param formatType the type of format
807 * @return the NumberFormat, or null.
810 public NumberFormat createFormat(Locale loc, int formatType) {
811 return createFormat(ULocale.forLocale(loc), formatType);
817 protected NumberFormatFactory() {
822 * A NumberFormatFactory that supports a single locale. It can be visible or invisible.
825 public static abstract class SimpleNumberFormatFactory extends NumberFormatFactory {
826 final Set<String> localeNames;
827 final boolean visible;
830 * Constructs a SimpleNumberFormatFactory with the given locale.
833 public SimpleNumberFormatFactory(Locale locale) {
838 * Constructs a SimpleNumberFormatFactory with the given locale and the
842 public SimpleNumberFormatFactory(Locale locale, boolean visible) {
843 localeNames = Collections.singleton(ULocale.forLocale(locale).getBaseName());
844 this.visible = visible;
848 * Constructs a SimpleNumberFormatFactory with the given locale.
851 public SimpleNumberFormatFactory(ULocale locale) {
856 * Constructs a SimpleNumberFormatFactory with the given locale and the
860 public SimpleNumberFormatFactory(ULocale locale, boolean visible) {
861 localeNames = Collections.singleton(locale.getBaseName());
862 this.visible = visible;
869 public final boolean visible() {
877 public final Set<String> getSupportedLocaleNames() {
882 // shim so we can build without service code
883 static abstract class NumberFormatShim {
884 abstract Locale[] getAvailableLocales();
885 abstract ULocale[] getAvailableULocales();
886 abstract Object registerFactory(NumberFormatFactory f);
887 abstract boolean unregister(Object k);
888 abstract NumberFormat createInstance(ULocale l, int k);
891 private static NumberFormatShim shim;
892 private static NumberFormatShim getShim() {
893 // Note: this instantiation is safe on loose-memory-model configurations
894 // despite lack of synchronization, since the shim instance has no state--
895 // it's all in the class init. The worst problem is we might instantiate
896 // two shim instances, but they'll share the same state so that's ok.
899 Class<?> cls = Class.forName("com.ibm.icu.text.NumberFormatServiceShim");
900 shim = (NumberFormatShim)cls.newInstance();
903 catch (MissingResourceException e){
906 catch (Exception e) {
907 // e.printStackTrace();
908 throw new RuntimeException(e.getMessage());
916 * Returns the list of Locales for which NumberFormats are available.
917 * @return the available locales
920 public static Locale[] getAvailableLocales() {
922 return ICUResourceBundle.getAvailableLocales();
924 return getShim().getAvailableLocales();
928 * {@icu} Returns the list of Locales for which NumberFormats are available.
929 * @return the available locales
930 * @draft ICU 3.2 (retain)
931 * @provisional This API might change or be removed in a future release.
933 public static ULocale[] getAvailableULocales() {
935 return ICUResourceBundle.getAvailableULocales();
937 return getShim().getAvailableULocales();
941 * {@icu} Registers a new NumberFormatFactory. The factory is adopted by
942 * the service and must not be modified. The returned object is a
943 * key that can be used to unregister this factory.
944 * @param factory the factory to register
945 * @return a key with which to unregister the factory
948 public static Object registerFactory(NumberFormatFactory factory) {
949 if (factory == null) {
950 throw new IllegalArgumentException("factory must not be null");
952 return getShim().registerFactory(factory);
956 * {@icu} Unregisters the factory or instance associated with this key (obtained from
957 * registerInstance or registerFactory).
958 * @param registryKey a key obtained from registerFactory
959 * @return true if the object was successfully unregistered
962 public static boolean unregister(Object registryKey) {
963 if (registryKey == null) {
964 throw new IllegalArgumentException("registryKey must not be null");
971 return shim.unregister(registryKey);
974 // ===== End of factory stuff =====
977 * Overrides hashCode.
980 public int hashCode() {
981 return maximumIntegerDigits * 37 + maxFractionDigits;
982 // just enough fields for a reasonable distribution
987 * Two NumberFormats are equal if they are of the same class
988 * and the settings (groupingUsed, parseIntegerOnly, maximumIntegerDigits, etc.
990 * @param obj the object to compare against
991 * @return true if the object is equal to this.
994 public boolean equals(Object obj) {
995 if (obj == null) return false;
998 if (getClass() != obj.getClass())
1000 NumberFormat other = (NumberFormat) obj;
1001 return maximumIntegerDigits == other.maximumIntegerDigits
1002 && minimumIntegerDigits == other.minimumIntegerDigits
1003 && maximumFractionDigits == other.maximumFractionDigits
1004 && minimumFractionDigits == other.minimumFractionDigits
1005 && groupingUsed == other.groupingUsed
1006 && parseIntegerOnly == other.parseIntegerOnly
1007 && parseStrict == other.parseStrict;
1014 public Object clone() {
1015 NumberFormat other = (NumberFormat) super.clone();
1020 * Returns true if grouping is used in this format. For example, in the
1021 * en_US locale, with grouping on, the number 1234567 will be formatted
1022 * as "1,234,567". The grouping separator as well as the size of each group
1023 * is locale-dependent and is determined by subclasses of NumberFormat.
1024 * Grouping affects both parsing and formatting.
1025 * @return true if grouping is used
1026 * @see #setGroupingUsed
1029 public boolean isGroupingUsed() {
1030 return groupingUsed;
1034 * Sets whether or not grouping will be used in this format. Grouping
1035 * affects both parsing and formatting.
1036 * @see #isGroupingUsed
1037 * @param newValue true to use grouping.
1040 public void setGroupingUsed(boolean newValue) {
1041 groupingUsed = newValue;
1045 * Returns the maximum number of digits allowed in the integer portion of a
1046 * number. The default value is 40, which subclasses can override.
1047 * When formatting, the exact behavior when this value is exceeded is
1048 * subclass-specific. When parsing, this has no effect.
1049 * @return the maximum number of integer digits
1050 * @see #setMaximumIntegerDigits
1053 public int getMaximumIntegerDigits() {
1054 return maximumIntegerDigits;
1058 * Sets the maximum number of digits allowed in the integer portion of a
1059 * number. This must be >= minimumIntegerDigits. If the
1060 * new value for maximumIntegerDigits is less than the current value
1061 * of minimumIntegerDigits, then minimumIntegerDigits will also be set to
1063 * @param newValue the maximum number of integer digits to be shown; if
1064 * less than zero, then zero is used. Subclasses might enforce an
1065 * upper limit to this value appropriate to the numeric type being formatted.
1066 * @see #getMaximumIntegerDigits
1069 public void setMaximumIntegerDigits(int newValue) {
1070 maximumIntegerDigits = Math.max(0,newValue);
1071 if (minimumIntegerDigits > maximumIntegerDigits)
1072 minimumIntegerDigits = maximumIntegerDigits;
1076 * Returns the minimum number of digits allowed in the integer portion of a
1077 * number. The default value is 1, which subclasses can override.
1078 * When formatting, if this value is not reached, numbers are padded on the
1079 * left with the locale-specific '0' character to ensure at least this
1080 * number of integer digits. When parsing, this has no effect.
1081 * @return the minimum number of integer digits
1082 * @see #setMinimumIntegerDigits
1085 public int getMinimumIntegerDigits() {
1086 return minimumIntegerDigits;
1090 * Sets the minimum number of digits allowed in the integer portion of a
1091 * number. This must be <= maximumIntegerDigits. If the
1092 * new value for minimumIntegerDigits is more than the current value
1093 * of maximumIntegerDigits, then maximumIntegerDigits will also be set to
1095 * @param newValue the minimum number of integer digits to be shown; if
1096 * less than zero, then zero is used. Subclasses might enforce an
1097 * upper limit to this value appropriate to the numeric type being formatted.
1098 * @see #getMinimumIntegerDigits
1101 public void setMinimumIntegerDigits(int newValue) {
1102 minimumIntegerDigits = Math.max(0,newValue);
1103 if (minimumIntegerDigits > maximumIntegerDigits)
1104 maximumIntegerDigits = minimumIntegerDigits;
1108 * Returns the maximum number of digits allowed in the fraction
1109 * portion of a number. The default value is 3, which subclasses
1110 * can override. When formatting, the exact behavior when this
1111 * value is exceeded is subclass-specific. When parsing, this has
1113 * @return the maximum number of fraction digits
1114 * @see #setMaximumFractionDigits
1117 public int getMaximumFractionDigits() {
1118 return maximumFractionDigits;
1122 * Sets the maximum number of digits allowed in the fraction portion of a
1123 * number. This must be >= minimumFractionDigits. If the
1124 * new value for maximumFractionDigits is less than the current value
1125 * of minimumFractionDigits, then minimumFractionDigits will also be set to
1127 * @param newValue the maximum number of fraction digits to be shown; if
1128 * less than zero, then zero is used. The concrete subclass may enforce an
1129 * upper limit to this value appropriate to the numeric type being formatted.
1130 * @see #getMaximumFractionDigits
1133 public void setMaximumFractionDigits(int newValue) {
1134 maximumFractionDigits = Math.max(0,newValue);
1135 if (maximumFractionDigits < minimumFractionDigits)
1136 minimumFractionDigits = maximumFractionDigits;
1140 * Returns the minimum number of digits allowed in the fraction portion of a
1141 * number. The default value is 0, which subclasses can override.
1142 * When formatting, if this value is not reached, numbers are padded on
1143 * the right with the locale-specific '0' character to ensure at least
1144 * this number of fraction digits. When parsing, this has no effect.
1145 * @return the minimum number of fraction digits
1146 * @see #setMinimumFractionDigits
1149 public int getMinimumFractionDigits() {
1150 return minimumFractionDigits;
1154 * Sets the minimum number of digits allowed in the fraction portion of a
1155 * number. This must be <= maximumFractionDigits. If the
1156 * new value for minimumFractionDigits exceeds the current value
1157 * of maximumFractionDigits, then maximumFractionDigits will also be set to
1159 * @param newValue the minimum number of fraction digits to be shown; if
1160 * less than zero, then zero is used. Subclasses might enforce an
1161 * upper limit to this value appropriate to the numeric type being formatted.
1162 * @see #getMinimumFractionDigits
1165 public void setMinimumFractionDigits(int newValue) {
1166 minimumFractionDigits = Math.max(0,newValue);
1167 if (maximumFractionDigits < minimumFractionDigits)
1168 maximumFractionDigits = minimumFractionDigits;
1172 * Sets the <tt>Currency</tt> object used to display currency
1173 * amounts. This takes effect immediately, if this format is a
1174 * currency format. If this format is not a currency format, then
1175 * the currency object is used if and when this object becomes a
1177 * @param theCurrency new currency object to use. May be null for
1181 public void setCurrency(Currency theCurrency) {
1182 currency = theCurrency;
1186 * Returns the <tt>Currency</tt> object used to display currency
1187 * amounts. This may be null.
1190 public Currency getCurrency() {
1195 * Returns the currency in effect for this formatter. Subclasses
1196 * should override this method as needed. Unlike getCurrency(),
1197 * this method should never return null.
1198 * @return a non-null Currency
1200 * @deprecated This API is ICU internal only.
1202 protected Currency getEffectiveCurrency() {
1203 Currency c = getCurrency();
1205 ULocale uloc = getLocale(ULocale.VALID_LOCALE);
1207 uloc = ULocale.getDefault(Category.FORMAT);
1209 c = Currency.getInstance(uloc);
1215 * Returns the rounding mode used in this NumberFormat. The default implementation of
1216 * tis method in NumberFormat always throws <code>UnsupportedOperationException</code>.
1217 * @return A rounding mode, between <code>BigDecimal.ROUND_UP</code>
1218 * and <code>BigDecimal.ROUND_UNNECESSARY</code>.
1219 * @see #setRoundingMode(int)
1222 public int getRoundingMode() {
1223 throw new UnsupportedOperationException(
1224 "getRoundingMode must be implemented by the subclass implementation.");
1228 * Set the rounding mode used in this NumberFormat. The default implementation of
1229 * tis method in NumberFormat always throws <code>UnsupportedOperationException</code>.
1230 * @param roundingMode A rounding mode, between
1231 * <code>BigDecimal.ROUND_UP</code> and
1232 * <code>BigDecimal.ROUND_UNNECESSARY</code>.
1233 * @see #getRoundingMode()
1236 public void setRoundingMode(int roundingMode) {
1237 throw new UnsupportedOperationException(
1238 "setRoundingMode must be implemented by the subclass implementation.");
1243 * Returns a specific style number format for a specific locale.
1244 * @param desiredLocale the specific locale.
1245 * @param choice number format style
1246 * @throws IllegalArgumentException if choice is not one of
1247 * NUMBERSTYLE, CURRENCYSTYLE,
1248 * PERCENTSTYLE, SCIENTIFICSTYLE,
1250 * ISOCURRENCYSTYLE, PLURALCURRENCYSTYLE,
1253 public static NumberFormat getInstance(ULocale desiredLocale, int choice) {
1254 if (choice < NUMBERSTYLE || choice > PLURALCURRENCYSTYLE) {
1255 throw new IllegalArgumentException(
1256 "choice should be from NUMBERSTYLE to PLURALCURRENCYSTYLE");
1258 // if (shim == null) {
1259 // return createInstance(desiredLocale, choice);
1261 // // TODO: shims must call setLocale() on object they create
1262 // return getShim().createInstance(desiredLocale, choice);
1264 return getShim().createInstance(desiredLocale, choice);
1267 // =======================privates===============================
1269 static NumberFormat createInstance(ULocale desiredLocale, int choice) {
1270 // If the choice is PLURALCURRENCYSTYLE, the pattern is not a single
1271 // pattern, it is a pattern set, so we do not need to get them here.
1272 // If the choice is ISOCURRENCYSTYLE, the pattern is the currrency
1273 // pattern in the locale but by replacing the single currency sign
1274 // with double currency sign.
1275 String pattern = getPattern(desiredLocale, choice);
1276 DecimalFormatSymbols symbols = new DecimalFormatSymbols(desiredLocale);
1278 // Here we assume that the locale passed in is in the canonical
1279 // form, e.g: pt_PT_@currency=PTE not pt_PT_PREEURO
1280 // This style wont work for currency plural format.
1281 // For currency plural format, the pattern is get from
1282 // the locale (from CurrencyUnitPatterns) without override.
1283 if(choice == CURRENCYSTYLE || choice == ISOCURRENCYSTYLE){
1284 String temp = symbols.getCurrencyPattern();
1290 // replace single currency sign in the pattern with double currency sign
1291 // if the choice is ISOCURRENCYSTYLE.
1292 if (choice == ISOCURRENCYSTYLE) {
1293 pattern = pattern.replace("\u00A4", doubleCurrencyStr);
1296 // Get the numbering system
1297 NumberingSystem ns = NumberingSystem.getInstance(desiredLocale);
1302 NumberFormat format;
1304 if ( ns != null && ns.isAlgorithmic()) {
1306 String nsRuleSetGroup;
1307 String nsRuleSetName;
1309 int desiredRulesType = RuleBasedNumberFormat.NUMBERING_SYSTEM;
1311 nsDesc = ns.getDescription();
1312 int firstSlash = nsDesc.indexOf("/");
1313 int lastSlash = nsDesc.lastIndexOf("/");
1315 if ( lastSlash > firstSlash ) {
1316 String nsLocID = nsDesc.substring(0,firstSlash);
1317 nsRuleSetGroup = nsDesc.substring(firstSlash+1,lastSlash);
1318 nsRuleSetName = nsDesc.substring(lastSlash+1);
1320 nsLoc = new ULocale(nsLocID);
1321 if ( nsRuleSetGroup.equals("SpelloutRules")) {
1322 desiredRulesType = RuleBasedNumberFormat.SPELLOUT;
1325 nsLoc = desiredLocale;
1326 nsRuleSetName = nsDesc;
1329 RuleBasedNumberFormat r = new RuleBasedNumberFormat(nsLoc,desiredRulesType);
1330 r.setDefaultRuleSet(nsRuleSetName);
1333 DecimalFormat f = new DecimalFormat(pattern, symbols, choice);
1334 // System.out.println("loc: " + desiredLocale + " choice: " + choice + " pat: " + pattern + " sym: " + symbols + " result: " + format);
1337 Add codes for the new method getIntegerInstance() [Richard/GCL]
1339 // TODO: revisit this -- this is almost certainly not the way we want
1340 // to do this. aliu 1/6/2004
1341 if (choice == INTEGERSTYLE) {
1342 f.setMaximumFractionDigits(0);
1343 f.setDecimalSeparatorAlwaysShown(false);
1344 f.setParseIntegerOnly(true);
1348 // TODO: the actual locale of the *pattern* may differ from that
1349 // for the *symbols*. For now, we use the data for the symbols.
1351 ULocale valid = symbols.getLocale(ULocale.VALID_LOCALE);
1352 ULocale actual = symbols.getLocale(ULocale.ACTUAL_LOCALE);
1353 format.setLocale(valid, actual);
1359 * Returns the pattern for the provided locale and choice.
1360 * @param forLocale the locale of the data.
1361 * @param choice the pattern format.
1362 * @return the pattern
1363 * @deprecated ICU 3.4 subclassers should override getPattern(ULocale, int) instead of this method.
1365 protected static String getPattern(Locale forLocale, int choice) {
1366 return getPattern(ULocale.forLocale(forLocale), choice);
1370 * Returns the pattern for the provided locale and choice.
1371 * @param forLocale the locale of the data.
1372 * @param choice the pattern format.
1373 * @return the pattern
1376 protected static String getPattern(ULocale forLocale, int choice) {
1378 /* The following code takes care of a few cases where the
1379 * resource data in the underlying JDK lags the new features
1380 * we have added to ICU4J: scientific notation, rounding, and
1381 * secondary grouping.
1383 * We detect these cases here and return various hard-coded
1384 * resource data. This is the simplest solution for now, but
1385 * it is not a good long-term mechanism.
1387 * We should replace this code with a data-driven mechanism
1388 * that reads the bundle com.ibm.icu.impl.data.LocaleElements
1389 * and parses an exception table that overrides the standard
1390 * data at java.text.resource.LocaleElements*.java.
1391 * Alternatively, we should create our own copy of the
1392 * resource data, and use that exclusively.
1395 // TEMPORARY, until we get scientific patterns into the main
1396 // resources: Retrieve scientific patterns from our resources.
1397 //if (choice == SCIENTIFICSTYLE) {
1398 // Temporarily hard code; retrieve from resource later
1399 /*For ICU compatibility [Richard/GCL]*/
1401 // return NumberFormat.getBaseStringArray("NumberPatterns")[SCIENTIFICSTYLE];
1405 // Try the cache first
1406 String[] numberPatterns = (String[]) cachedLocaleData.get(forLocale);
1407 if (numberPatterns == null) {
1408 OverlayBundle resource = new OverlayBundle(new String[]
1409 { "com.ibm.icu.impl.data.LocaleElements", RESOURCE_BASE }, forLocale);
1410 numberPatterns = resource.getStringArray("NumberPatterns");
1412 cachedLocaleData.put(forLocale, numberPatterns);
1416 /* for ISOCURRENCYSTYLE and PLURALCURRENCYSTYLE,
1417 * the pattern is the same as the pattern of CURRENCYSTYLE
1418 * but by replacing the single currency sign with
1419 * double currency sign or triple currency sign.
1421 int entry = (choice == INTEGERSTYLE) ? NUMBERSTYLE :
1422 ((choice == ISOCURRENCYSTYLE || choice == PLURALCURRENCYSTYLE)?
1423 CURRENCYSTYLE : choice); //[Richard/GCL]
1425 ICUResourceBundle rb = (ICUResourceBundle)UResourceBundle.
1426 getBundleInstance(ICUResourceBundle.ICU_BASE_NAME, forLocale);
1427 String[] numberPatternKeys = { "decimalFormat", "currencyFormat", "percentFormat", "scientificFormat" };
1428 return rb.getStringWithFallback("NumberElements/latn/patterns/"+numberPatternKeys[entry]);
1430 // TODO: Make lookups of patterns depend on the locale's numbering system.
1431 // Right now we assume "latn" because no locales have any variations this way.
1432 // But we have the structure in CLDR to do this.
1437 * First, read in the default serializable data.
1439 * Then, if <code>serialVersionOnStream</code> is less than 1, indicating that
1440 * the stream was written by JDK 1.1,
1441 * set the <code>int</code> fields such as <code>maximumIntegerDigits</code>
1442 * to be equal to the <code>byte</code> fields such as <code>maxIntegerDigits</code>,
1443 * since the <code>int</code> fields were not present in JDK 1.1.
1444 * Finally, set serialVersionOnStream back to the maximum allowed value so that
1445 * default serialization will work properly if this object is streamed out again.
1447 private void readObject(ObjectInputStream stream)
1448 throws IOException, ClassNotFoundException
1450 stream.defaultReadObject();
1452 // we don't have serialization data for this format
1453 if (serialVersionOnStream < 1) {
1454 // Didn't have additional int fields, reassign to use them.
1455 maximumIntegerDigits = maxIntegerDigits;
1456 minimumIntegerDigits = minIntegerDigits;
1457 maximumFractionDigits = maxFractionDigits;
1458 minimumFractionDigits = minFractionDigits;
1462 Validate the min and max fields [Richard/GCL]
1464 if (minimumIntegerDigits > maximumIntegerDigits ||
1465 minimumFractionDigits > maximumFractionDigits ||
1466 minimumIntegerDigits < 0 || minimumFractionDigits < 0) {
1467 throw new InvalidObjectException("Digit count range invalid");
1469 serialVersionOnStream = currentSerialVersion;
1473 * Write out the default serializable data, after first setting
1474 * the <code>byte</code> fields such as <code>maxIntegerDigits</code> to be
1475 * equal to the <code>int</code> fields such as <code>maximumIntegerDigits</code>
1476 * (or to <code>Byte.MAX_VALUE</code>, whichever is smaller), for compatibility
1477 * with the JDK 1.1 version of the stream format.
1479 private void writeObject(ObjectOutputStream stream)
1482 maxIntegerDigits = (maximumIntegerDigits > Byte.MAX_VALUE) ? Byte.MAX_VALUE :
1483 (byte)maximumIntegerDigits;
1484 minIntegerDigits = (minimumIntegerDigits > Byte.MAX_VALUE) ? Byte.MAX_VALUE :
1485 (byte)minimumIntegerDigits;
1486 maxFractionDigits = (maximumFractionDigits > Byte.MAX_VALUE) ? Byte.MAX_VALUE :
1487 (byte)maximumFractionDigits;
1488 minFractionDigits = (minimumFractionDigits > Byte.MAX_VALUE) ? Byte.MAX_VALUE :
1489 (byte)minimumFractionDigits;
1490 stream.defaultWriteObject();
1493 // Unused -- Alan 2003-05
1495 // * Cache to hold the NumberPatterns of a Locale.
1497 // private static final Hashtable cachedLocaleData = new Hashtable(3);
1499 private static final char[] doubleCurrencySign = {0xA4, 0xA4};
1500 private static final String doubleCurrencyStr = new String(doubleCurrencySign);
1503 Add Field for the new method getIntegerInstance() [Richard/GCL]
1508 * True if the the grouping (i.e. thousands) separator is used when
1509 * formatting and parsing numbers.
1512 * @see #isGroupingUsed
1514 private boolean groupingUsed = true;
1517 * The maximum number of digits allowed in the integer portion of a
1518 * number. <code>maxIntegerDigits</code> must be greater than or equal to
1519 * <code>minIntegerDigits</code>.
1521 * <strong>Note:</strong> This field exists only for serialization
1522 * compatibility with JDK 1.1. In JDK 1.2 and higher, the new
1523 * <code>int</code> field <code>maximumIntegerDigits</code> is used instead.
1524 * When writing to a stream, <code>maxIntegerDigits</code> is set to
1525 * <code>maximumIntegerDigits</code> or <code>Byte.MAX_VALUE</code>,
1526 * whichever is smaller. When reading from a stream, this field is used
1527 * only if <code>serialVersionOnStream</code> is less than 1.
1530 * @see #getMaximumIntegerDigits
1532 private byte maxIntegerDigits = 40;
1535 * The minimum number of digits allowed in the integer portion of a
1536 * number. <code>minimumIntegerDigits</code> must be less than or equal to
1537 * <code>maximumIntegerDigits</code>.
1539 * <strong>Note:</strong> This field exists only for serialization
1540 * compatibility with JDK 1.1. In JDK 1.2 and higher, the new
1541 * <code>int</code> field <code>minimumIntegerDigits</code> is used instead.
1542 * When writing to a stream, <code>minIntegerDigits</code> is set to
1543 * <code>minimumIntegerDigits</code> or <code>Byte.MAX_VALUE</code>,
1544 * whichever is smaller. When reading from a stream, this field is used
1545 * only if <code>serialVersionOnStream</code> is less than 1.
1548 * @see #getMinimumIntegerDigits
1550 private byte minIntegerDigits = 1;
1553 * The maximum number of digits allowed in the fractional portion of a
1554 * number. <code>maximumFractionDigits</code> must be greater than or equal to
1555 * <code>minimumFractionDigits</code>.
1557 * <strong>Note:</strong> This field exists only for serialization
1558 * compatibility with JDK 1.1. In JDK 1.2 and higher, the new
1559 * <code>int</code> field <code>maximumFractionDigits</code> is used instead.
1560 * When writing to a stream, <code>maxFractionDigits</code> is set to
1561 * <code>maximumFractionDigits</code> or <code>Byte.MAX_VALUE</code>,
1562 * whichever is smaller. When reading from a stream, this field is used
1563 * only if <code>serialVersionOnStream</code> is less than 1.
1566 * @see #getMaximumFractionDigits
1568 private byte maxFractionDigits = 3; // invariant, >= minFractionDigits
1571 * The minimum number of digits allowed in the fractional portion of a
1572 * number. <code>minimumFractionDigits</code> must be less than or equal to
1573 * <code>maximumFractionDigits</code>.
1575 * <strong>Note:</strong> This field exists only for serialization
1576 * compatibility with JDK 1.1. In JDK 1.2 and higher, the new
1577 * <code>int</code> field <code>minimumFractionDigits</code> is used instead.
1578 * When writing to a stream, <code>minFractionDigits</code> is set to
1579 * <code>minimumFractionDigits</code> or <code>Byte.MAX_VALUE</code>,
1580 * whichever is smaller. When reading from a stream, this field is used
1581 * only if <code>serialVersionOnStream</code> is less than 1.
1584 * @see #getMinimumFractionDigits
1586 private byte minFractionDigits = 0;
1589 * True if this format will parse numbers as integers only.
1592 * @see #isParseIntegerOnly
1594 private boolean parseIntegerOnly = false;
1596 // new fields for 1.2. byte is too small for integer digits.
1599 * The maximum number of digits allowed in the integer portion of a
1600 * number. <code>maximumIntegerDigits</code> must be greater than or equal to
1601 * <code>minimumIntegerDigits</code>.
1604 * @see #getMaximumIntegerDigits
1606 private int maximumIntegerDigits = 40;
1609 * The minimum number of digits allowed in the integer portion of a
1610 * number. <code>minimumIntegerDigits</code> must be less than or equal to
1611 * <code>maximumIntegerDigits</code>.
1614 * @see #getMinimumIntegerDigits
1616 private int minimumIntegerDigits = 1;
1619 * The maximum number of digits allowed in the fractional portion of a
1620 * number. <code>maximumFractionDigits</code> must be greater than or equal to
1621 * <code>minimumFractionDigits</code>.
1624 * @see #getMaximumFractionDigits
1626 private int maximumFractionDigits = 3; // invariant, >= minFractionDigits
1629 * The minimum number of digits allowed in the fractional portion of a
1630 * number. <code>minimumFractionDigits</code> must be less than or equal to
1631 * <code>maximumFractionDigits</code>.
1634 * @see #getMinimumFractionDigits
1636 private int minimumFractionDigits = 0;
1639 * Currency object used to format currencies. Subclasses may
1640 * ignore this if they are not currency formats. This will be
1641 * null unless a subclass sets it to a non-null value.
1644 private Currency currency;
1646 static final int currentSerialVersion = 1;
1649 * Describes the version of <code>NumberFormat</code> present on the stream.
1650 * Possible values are:
1652 * <li><b>0</b> (or uninitialized): the JDK 1.1 version of the stream format.
1653 * In this version, the <code>int</code> fields such as
1654 * <code>maximumIntegerDigits</code> were not present, and the <code>byte</code>
1655 * fields such as <code>maxIntegerDigits</code> are used instead.
1657 * <li><b>1</b>: the JDK 1.2 version of the stream format. The values of the
1658 * <code>byte</code> fields such as <code>maxIntegerDigits</code> are ignored,
1659 * and the <code>int</code> fields such as <code>maximumIntegerDigits</code>
1662 * When streaming out a <code>NumberFormat</code>, the most recent format
1663 * (corresponding to the highest allowable <code>serialVersionOnStream</code>)
1664 * is always written.
1668 private int serialVersionOnStream = currentSerialVersion;
1670 // Removed "implements Cloneable" clause. Needs to update serialization
1671 // ID for backward compatibility.
1672 private static final long serialVersionUID = -2308460125733713944L;
1675 * Empty constructor. Public for compatibily with JDK which lets the
1676 * compiler generate a default public constructor even though this is
1677 * an abstract class.
1680 public NumberFormat() {
1684 private boolean parseStrict;
1687 * The instances of this inner class are used as attribute keys and values
1688 * in AttributedCharacterIterator that
1689 * NumberFormat.formatToCharacterIterator() method returns.
1691 * There is no public constructor to this class, the only instances are the
1692 * constants defined here.
1696 public static class Field extends Format.Field {
1697 // generated by serialver from JDK 1.4.1_01
1698 static final long serialVersionUID = -4516273749929385842L;
1703 public static final Field SIGN = new Field("sign");
1708 public static final Field INTEGER = new Field("integer");
1713 public static final Field FRACTION = new Field("fraction");
1718 public static final Field EXPONENT = new Field("exponent");
1723 public static final Field EXPONENT_SIGN = new Field("exponent sign");
1728 public static final Field EXPONENT_SYMBOL = new Field("exponent symbol");
1733 public static final Field DECIMAL_SEPARATOR = new Field("decimal separator");
1737 public static final Field GROUPING_SEPARATOR = new Field("grouping separator");
1742 public static final Field PERCENT = new Field("percent");
1747 public static final Field PERMILLE = new Field("per mille");
1752 public static final Field CURRENCY = new Field("currency");
1755 * Constructs a new instance of NumberFormat.Field with the given field
1759 protected Field(String fieldName) {
1764 * serizalization method resolve instances to the constant
1765 * NumberFormat.Field values
1768 protected Object readResolve() throws InvalidObjectException {
1769 if (this.getName().equals(INTEGER.getName()))
1771 if (this.getName().equals(FRACTION.getName()))
1773 if (this.getName().equals(EXPONENT.getName()))
1775 if (this.getName().equals(EXPONENT_SIGN.getName()))
1776 return EXPONENT_SIGN;
1777 if (this.getName().equals(EXPONENT_SYMBOL.getName()))
1778 return EXPONENT_SYMBOL;
1779 if (this.getName().equals(CURRENCY.getName()))
1781 if (this.getName().equals(DECIMAL_SEPARATOR.getName()))
1782 return DECIMAL_SEPARATOR;
1783 if (this.getName().equals(GROUPING_SEPARATOR.getName()))
1784 return GROUPING_SEPARATOR;
1785 if (this.getName().equals(PERCENT.getName()))
1787 if (this.getName().equals(PERMILLE.getName()))
1789 if (this.getName().equals(SIGN.getName()))
1792 throw new InvalidObjectException("An invalid object.");