]> gitweb.fperrin.net Git - Dictionary.git/blob - jars/icu4j-4_8_1_1/main/classes/core/src/com/ibm/icu/text/NumberFormat.java
Added flags.
[Dictionary.git] / jars / icu4j-4_8_1_1 / main / classes / core / src / com / ibm / icu / text / NumberFormat.java
1 /*
2  *******************************************************************************
3  * Copyright (C) 1996-2011, International Business Machines Corporation and    *
4  * others. All Rights Reserved.                                                *
5  *******************************************************************************
6  */
7
8 package com.ibm.icu.text;
9
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;
22 import java.util.Set;
23
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;
30
31 /**
32  * {@icuenhanced java.text.NumberFormat}.{@icu _usage_}
33  *
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.
38  *
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.
43  *
44  * <p>
45  * To format a number for the current Locale, use one of the factory
46  * class methods:
47  * <blockquote>
48  * <pre>
49  *  myString = NumberFormat.getInstance().format(myNumber);
50  * </pre>
51  * </blockquote>
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.
56  * <blockquote>
57  * <pre>
58  * NumberFormat nf = NumberFormat.getInstance();
59  * for (int i = 0; i < a.length; ++i) {
60  *     output.println(nf.format(myNumber[i]) + "; ");
61  * }
62  * </pre>
63  * </blockquote>
64  * To format a number for a different Locale, specify it in the
65  * call to <code>getInstance</code>.
66  * <blockquote>
67  * <pre>
68  * NumberFormat nf = NumberFormat.getInstance(Locale.FRENCH);
69  * </pre>
70  * </blockquote>
71  * You can also use a <code>NumberFormat</code> to parse numbers:
72  * <blockquote>
73  * <pre>
74  * myNumber = nf.parse(myString);
75  * </pre>
76  * </blockquote>
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%.
83  *
84  * <p>
85  * Starting from ICU 4.2, you can use getInstance() by passing in a 'style'
86  * as parameter to get the correct instance.
87  * For example,
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".
99  *
100  *
101  * <p>
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.
110  *
111  * <p>
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,
115  * <p>
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.
122  * <p>
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
125  * allow you to:
126  * <ul>
127  * <li> progressively parse through pieces of a string
128  * <li> align the decimal point and other areas
129  * </ul>
130  * For example, you can align numbers in two ways:
131  * <ol>
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.
138  *
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.
147  * </ol>
148  *
149  * <h4>Synchronization</h4>
150  * <p>
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.
154  * <p>
155  *
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>
160  *
161  * see          DecimalFormat
162  * see          java.text.ChoiceFormat
163  * @author       Mark Davis
164  * @author       Helena Shih
165  * @author       Alan Liu
166  * @stable ICU 2.0
167  */
168 public abstract class NumberFormat extends UFormat {
169
170     /**
171      * {@icu} Constant to specify normal number style of format.
172      * @stable ICU 4.2
173      */
174     public static final int NUMBERSTYLE = 0;
175     /**
176      * {@icu} Constant to specify currency style of format which uses currency symbol
177      * to represent currency, for example: "$3.00".
178      * @stable ICU 4.2
179      */
180     public static final int CURRENCYSTYLE = 1;
181     /**
182      * {@icu} Constant to specify a style of format to display percent.
183      * @stable ICU 4.2
184      */
185     public static final int PERCENTSTYLE = 2;
186     /**
187      * {@icu} Constant to specify a style of format to display scientific number.
188      * @stable ICU 4.2
189      */
190     public static final int SCIENTIFICSTYLE = 3;
191     /**
192      * {@icu} Constant to specify a integer number style format.
193      * @stable ICU 4.2
194      */
195     public static final int INTEGERSTYLE = 4;
196     /**
197      * {@icu} Constant to specify currency style of format which uses currency
198      * ISO code to represent currency, for example: "USD3.00".
199      * @stable ICU 4.2
200      */
201     public static final int ISOCURRENCYSTYLE = 5;
202     /**
203      * {@icu} Constant to specify currency style of format which uses currency
204      * long name with plural format to represent currency, for example,
205      * "3.00 US Dollars".
206      * @stable ICU 4.2
207      */
208     public static final int PLURALCURRENCYSTYLE = 6;
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      * @stable ICU 2.0
215      */
216     public static final int INTEGER_FIELD = 0;
217
218     /**
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
222      * @stable ICU 2.0
223      */
224     public static final int FRACTION_FIELD = 1;
225
226     /**
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)
231      * @stable ICU 2.0
232      */
233     public StringBuffer format(Object number,
234                                StringBuffer toAppendTo,
235                                FieldPosition pos) {
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);
248         } else {
249             throw new IllegalArgumentException("Cannot format given Object as a Number");
250         }
251     }
252
253     /**
254      * Parses text from a string to produce a 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)
259      * @stable ICU 2.0
260      */
261     public final Object parseObject(String source,
262                                     ParsePosition parsePosition) {
263         return parse(source, parsePosition);
264     }
265
266     /**
267      * Specialization of format.
268      * @see java.text.Format#format(Object)
269      * @stable ICU 2.0
270      */
271     public final String format(double number) {
272         return format(number,new StringBuffer(),
273                       new FieldPosition(0)).toString();
274     }
275
276     /**
277      * Specialization of format.
278      * @see java.text.Format#format(Object)
279      * @stable ICU 2.0
280      */
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();
286     }
287
288     /**
289      * {@icu} Convenience method to format a BigInteger.
290      * @stable ICU 2.0
291      */
292     public final String format(BigInteger number) {
293         return format(number, new StringBuffer(),
294                       new FieldPosition(0)).toString();
295     }
296
297     /**
298      * Convenience method to format a BigDecimal.
299      * @stable ICU 2.0
300      */
301     public final String format(java.math.BigDecimal number) {
302         return format(number, new StringBuffer(),
303                       new FieldPosition(0)).toString();
304     }
305
306     /**
307      * {@icu} Convenience method to format an ICU BigDecimal.
308      * @stable ICU 2.0
309      */
310     public final String format(com.ibm.icu.math.BigDecimal number) {
311         return format(number, new StringBuffer(),
312                       new FieldPosition(0)).toString();
313     }
314
315     /**
316      * {@icu} Convenience method to format a CurrencyAmount.
317      * @stable ICU 3.0
318      */
319     public final String format(CurrencyAmount currAmt) {
320         return format(currAmt, new StringBuffer(),
321                       new FieldPosition(0)).toString();
322     }
323
324     /**
325      * Specialization of format.
326      * @see java.text.Format#format(Object, StringBuffer, FieldPosition)
327      * @stable ICU 2.0
328      */
329     public abstract StringBuffer format(double number,
330                                         StringBuffer toAppendTo,
331                                         FieldPosition pos);
332
333     /**
334      * Specialization of format.
335      * @see java.text.Format#format(Object, StringBuffer, FieldPosition)
336      * @stable ICU 2.0
337      */
338     public abstract StringBuffer format(long number,
339                                         StringBuffer toAppendTo,
340                                         FieldPosition pos);
341     /**
342      * {@icu} Formats a BigInteger. Specialization of format.
343      * @see java.text.Format#format(Object, StringBuffer, FieldPosition)
344      * @stable ICU 2.0
345      */
346     public abstract StringBuffer format(BigInteger number,
347                                         StringBuffer toAppendTo,
348                                         FieldPosition pos);
349     /**
350      * {@icu} Formats a BigDecimal. Specialization of format.
351      * @see java.text.Format#format(Object, StringBuffer, FieldPosition)
352      * @stable ICU 2.0
353      */
354     public abstract StringBuffer format(java.math.BigDecimal number,
355                                         StringBuffer toAppendTo,
356                                         FieldPosition pos);
357     /**
358      * {@icu} Formats an ICU BigDecimal. Specialization of format.
359      * @see java.text.Format#format(Object, StringBuffer, FieldPosition)
360      * @stable ICU 2.0
361      */
362     public abstract StringBuffer format(com.ibm.icu.math.BigDecimal number,
363                                         StringBuffer toAppendTo,
364                                         FieldPosition pos);
365     /**
366      * {@icu} Formats a CurrencyAmount. Specialization of format.
367      * @see java.text.Format#format(Object, StringBuffer, FieldPosition)
368      * @stable ICU 3.0
369      */
370     public StringBuffer format(CurrencyAmount currAmt,
371                                StringBuffer toAppendTo,
372                                FieldPosition pos) {
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);
379         return toAppendTo;
380     }
381
382     /**
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
387      * after the 1).
388      * Does not throw an exception; if no object can be parsed, index is
389      * unchanged!
390      * @see #isParseIntegerOnly
391      * @see java.text.Format#parseObject(String, ParsePosition)
392      * @stable ICU 2.0
393      */
394     public abstract Number parse(String text, ParsePosition parsePosition);
395
396     /**
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.
399      *
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
403      * cannot be parsed.
404      * @see #format
405      * @stable ICU 2.0
406      */
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());
414         }
415         return result;
416     }
417
418     /**
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.
426      *
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
433      * @internal
434      */
435     public CurrencyAmount parseCurrency(String text, ParsePosition pos) {
436         ///CLOVER:OFF
437         // Default implementation only -- subclasses should override
438         Number n = parse(text, pos);
439         return n == null ? null : new CurrencyAmount(n, getEffectiveCurrency());
440         ///CLOVER:ON
441     }
442
443     /**
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
449      * subclass.
450      * @return true if this will parse integers only
451      * @stable ICU 2.0
452      */
453     public boolean isParseIntegerOnly() {
454         return parseIntegerOnly;
455     }
456
457     /**
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
461      * @stable ICU 2.0
462      */
463     public void setParseIntegerOnly(boolean value) {
464         parseIntegerOnly = value;
465     }
466
467     /**
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>
477      * </ul>
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
482      * @stable ICU 3.6
483      */
484     public void setParseStrict(boolean value) {
485         parseStrict = value;
486     }
487
488     /**
489      * {@icu} Returns whether strict parsing is in effect.
490      * @return true if strict parsing is in effect
491      * @see #setParseStrict
492      * @stable ICU 3.6
493      */
494     public boolean isParseStrict() {
495         return parseStrict;
496     }
497
498     //============== Locale Stuff =====================
499
500     /**
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
507      * @stable ICU 2.0
508      */
509     //Bug 4408066 [Richard/GCL]
510     public final static NumberFormat getInstance() {
511         return getInstance(ULocale.getDefault(Category.FORMAT), NUMBERSTYLE);
512     }
513
514     /**
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.
519      * @stable ICU 2.0
520      */
521     public static NumberFormat getInstance(Locale inLocale) {
522         return getInstance(ULocale.forLocale(inLocale), NUMBERSTYLE);
523     }
524
525     /**
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.
530      * @stable ICU 3.2
531      */
532     public static NumberFormat getInstance(ULocale inLocale) {
533         return getInstance(inLocale, NUMBERSTYLE);
534     }
535
536     /**
537      * {@icu} Returns a specific style number format for default <code>FORMAT</code> locale.
538      * @param style  number format style
539      * @see Category#FORMAT
540      * @stable ICU 4.2
541      */
542     public final static NumberFormat getInstance(int style) {
543         return getInstance(ULocale.getDefault(Category.FORMAT), style);
544     }
545
546     /**
547      * {@icu} Returns a specific style number format for a specific locale.
548      * @param inLocale  the specific locale.
549      * @param style     number format style
550      * @stable ICU 4.2
551      */
552     public static NumberFormat getInstance(Locale inLocale, int style) {
553         return getInstance(ULocale.forLocale(inLocale), style);
554     }
555
556
557     /**
558      * Returns a general-purpose number format for the current default <code>FORMAT</code> locale.
559      * @see Category#FORMAT
560      * @stable ICU 2.0
561      */
562     public final static NumberFormat getNumberInstance() {
563         return getInstance(ULocale.getDefault(Category.FORMAT), NUMBERSTYLE);
564     }
565
566     /**
567      * Returns a general-purpose number format for the specified locale.
568      * @stable ICU 2.0
569      */
570     public static NumberFormat getNumberInstance(Locale inLocale) {
571         return getInstance(ULocale.forLocale(inLocale), NUMBERSTYLE);
572     }
573
574     /**
575      * {@icu} Returns a general-purpose number format for the specified locale.
576      * @stable ICU 3.2
577      */
578     public static NumberFormat getNumberInstance(ULocale inLocale) {
579         return getInstance(inLocale, NUMBERSTYLE);
580     }
581
582     /**
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}).
589      *
590      * @return a number format for integer values
591      * @see Category#FORMAT
592      * @stable ICU 2.0
593      */
594     //Bug 4408066 [Richard/GCL]
595     public final static NumberFormat getIntegerInstance() {
596         return getInstance(ULocale.getDefault(Category.FORMAT), INTEGERSTYLE);
597     }
598
599     /**
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}).
606      *
607      * @param inLocale the locale for which a number format is needed
608      * @return a number format for integer values
609      * @stable ICU 2.0
610      */
611     //Bug 4408066 [Richard/GCL]
612     public static NumberFormat getIntegerInstance(Locale inLocale) {
613         return getInstance(ULocale.forLocale(inLocale), INTEGERSTYLE);
614     }
615
616     /**
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}).
623      *
624      * @param inLocale the locale for which a number format is needed
625      * @return a number format for integer values
626      * @stable ICU 3.2
627      */
628     public static NumberFormat getIntegerInstance(ULocale inLocale) {
629         return getInstance(inLocale, INTEGERSTYLE);
630     }
631
632     /**
633      * Returns a currency format for the current default <code>FORMAT</code> locale.
634      * @return a number format for currency
635      * @see Category#FORMAT
636      * @stable ICU 2.0
637      */
638     public final static NumberFormat getCurrencyInstance() {
639         return getInstance(ULocale.getDefault(Category.FORMAT), CURRENCYSTYLE);
640     }
641
642     /**
643      * Returns a currency format for the specified locale.
644      * @return a number format for currency
645      * @stable ICU 2.0
646      */
647     public static NumberFormat getCurrencyInstance(Locale inLocale) {
648         return getInstance(ULocale.forLocale(inLocale), CURRENCYSTYLE);
649     }
650
651     /**
652      * {@icu} Returns a currency format for the specified locale.
653      * @return a number format for currency
654      * @stable ICU 3.2
655      */
656     public static NumberFormat getCurrencyInstance(ULocale inLocale) {
657         return getInstance(inLocale, CURRENCYSTYLE);
658     }
659
660     /**
661      * Returns a percentage format for the current default <code>FORMAT</code> locale.
662      * @return a number format for percents
663      * @see Category#FORMAT
664      * @stable ICU 2.0
665      */
666     public final static NumberFormat getPercentInstance() {
667         return getInstance(ULocale.getDefault(Category.FORMAT), PERCENTSTYLE);
668     }
669
670     /**
671      * Returns a percentage format for the specified locale.
672      * @return a number format for percents
673      * @stable ICU 2.0
674      */
675     public static NumberFormat getPercentInstance(Locale inLocale) {
676         return getInstance(ULocale.forLocale(inLocale), PERCENTSTYLE);
677     }
678
679     /**
680      * {@icu} Returns a percentage format for the specified locale.
681      * @return a number format for percents
682      * @stable ICU 3.2
683      */
684     public static NumberFormat getPercentInstance(ULocale inLocale) {
685         return getInstance(inLocale, PERCENTSTYLE);
686     }
687
688     /**
689      * {@icu} Returns a scientific format for the current default <code>FORMAT</code> locale.
690      * @return a scientific number format
691      * @see Category#FORMAT
692      * @stable ICU 2.0
693      */
694     public final static NumberFormat getScientificInstance() {
695         return getInstance(ULocale.getDefault(Category.FORMAT), SCIENTIFICSTYLE);
696     }
697
698     /**
699      * {@icu} Returns a scientific format for the specified locale.
700      * @return a scientific number format
701      * @stable ICU 2.0
702      */
703     public static NumberFormat getScientificInstance(Locale inLocale) {
704         return getInstance(ULocale.forLocale(inLocale), SCIENTIFICSTYLE);
705     }
706
707     /**
708      * {@icu} Returns a scientific format for the specified locale.
709      * @return a scientific number format
710      * @stable ICU 3.2
711      */
712     public static NumberFormat getScientificInstance(ULocale inLocale) {
713         return getInstance(inLocale, SCIENTIFICSTYLE);
714     }
715
716     // ===== Factory stuff =====
717     /**
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.
722      *
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
727      * loop will occur.
728      *
729      * @stable ICU 2.6
730      */
731     public static abstract class NumberFormatFactory {
732         /**
733          * Value passed to format requesting a default number format.
734          * @stable ICU 2.6
735          */
736         public static final int FORMAT_NUMBER = NUMBERSTYLE;
737
738         /**
739          * Value passed to format requesting a currency format.
740          * @stable ICU 2.6
741          */
742         public static final int FORMAT_CURRENCY = CURRENCYSTYLE;
743
744         /**
745          * Value passed to format requesting a percent format.
746          * @stable ICU 2.6
747          */
748         public static final int FORMAT_PERCENT = PERCENTSTYLE;
749
750         /**
751          * Value passed to format requesting a scientific format.
752          * @stable ICU 2.6
753          */
754         public static final int FORMAT_SCIENTIFIC = SCIENTIFICSTYLE;
755
756         /**
757          * Value passed to format requesting an integer format.
758          * @stable ICU 2.6
759          */
760         public static final int FORMAT_INTEGER = INTEGERSTYLE;
761
762         /**
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.
767          * @stable ICU 2.6
768          */
769         public boolean visible() {
770             return true;
771         }
772
773         /**
774          * Returns an immutable collection of the locale names directly
775          * supported by this factory.
776          * @return the supported locale names.
777          * @stable ICU 2.6
778          */
779          public abstract Set<String> getSupportedLocaleNames();
780
781         /**
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.
791          * @stable ICU 3.2
792          */
793         public NumberFormat createFormat(ULocale loc, int formatType) {
794             return createFormat(loc.toLocale(), formatType);
795         }
796
797         /**
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.
808          * @stable ICU 2.6
809          */
810         public NumberFormat createFormat(Locale loc, int formatType) {
811             return createFormat(ULocale.forLocale(loc), formatType);
812         }
813
814         /**
815          * @stable ICU 2.6
816          */
817         protected NumberFormatFactory() {
818         }
819     }
820
821     /**
822      * A NumberFormatFactory that supports a single locale.  It can be visible or invisible.
823      * @stable ICU 2.6
824      */
825     public static abstract class SimpleNumberFormatFactory extends NumberFormatFactory {
826         final Set<String> localeNames;
827         final boolean visible;
828
829         /**
830          * Constructs a SimpleNumberFormatFactory with the given locale.
831          * @stable ICU 2.6
832          */
833         public SimpleNumberFormatFactory(Locale locale) {
834             this(locale, true);
835         }
836
837         /**
838          * Constructs a SimpleNumberFormatFactory with the given locale and the
839          * visibility.
840          * @stable ICU 2.6
841          */
842         public SimpleNumberFormatFactory(Locale locale, boolean visible) {
843             localeNames = Collections.singleton(ULocale.forLocale(locale).getBaseName());
844             this.visible = visible;
845         }
846
847         /**
848          * Constructs a SimpleNumberFormatFactory with the given locale.
849          * @stable ICU 3.2
850          */
851         public SimpleNumberFormatFactory(ULocale locale) {
852             this(locale, true);
853         }
854
855         /**
856          * Constructs a SimpleNumberFormatFactory with the given locale and the
857          * visibility.
858          * @stable ICU 3.2
859          */
860         public SimpleNumberFormatFactory(ULocale locale, boolean visible) {
861             localeNames = Collections.singleton(locale.getBaseName());
862             this.visible = visible;
863         }
864
865         /**
866          * {@inheritDoc}
867          * @stable ICU 2.6
868          */
869         public final boolean visible() {
870             return visible;
871         }
872
873         /**
874          * {@inheritDoc}
875          * @stable ICU 2.6
876          */
877         public final Set<String> getSupportedLocaleNames() {
878             return localeNames;
879         }
880     }
881
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);
889     }
890
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.
897         if (shim == null) {
898             try {
899                 Class<?> cls = Class.forName("com.ibm.icu.text.NumberFormatServiceShim");
900                 shim = (NumberFormatShim)cls.newInstance();
901             }
902             ///CLOVER:OFF
903             catch (MissingResourceException e){
904                 throw e;
905             }
906             catch (Exception e) {
907                // e.printStackTrace();
908                 throw new RuntimeException(e.getMessage());
909             }
910             ///CLOVER:ON
911         }
912         return shim;
913     }
914
915     /**
916      * Returns the list of Locales for which NumberFormats are available.
917      * @return the available locales
918      * @stable ICU 2.0
919      */
920     public static Locale[] getAvailableLocales() {
921         if (shim == null) {
922             return ICUResourceBundle.getAvailableLocales();
923         }
924         return getShim().getAvailableLocales();
925     }
926
927     /**
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.
932      */
933     public static ULocale[] getAvailableULocales() {
934         if (shim == null) {
935             return ICUResourceBundle.getAvailableULocales();
936         }
937         return getShim().getAvailableULocales();
938     }
939
940     /**
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
946      * @stable ICU 2.6
947      */
948     public static Object registerFactory(NumberFormatFactory factory) {
949         if (factory == null) {
950             throw new IllegalArgumentException("factory must not be null");
951         }
952         return getShim().registerFactory(factory);
953     }
954
955     /**
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
960      * @stable ICU 2.6
961      */
962     public static boolean unregister(Object registryKey) {
963         if (registryKey == null) {
964             throw new IllegalArgumentException("registryKey must not be null");
965         }
966
967         if (shim == null) {
968             return false;
969         }
970
971         return shim.unregister(registryKey);
972     }
973
974     // ===== End of factory stuff =====
975
976     /**
977      * Overrides hashCode.
978      * @stable ICU 2.0
979      */
980     public int hashCode() {
981         return maximumIntegerDigits * 37 + maxFractionDigits;
982         // just enough fields for a reasonable distribution
983     }
984
985     /**
986      * Overrides equals.
987      * Two NumberFormats are equal if they are of the same class
988      * and the settings (groupingUsed, parseIntegerOnly, maximumIntegerDigits, etc.
989      * are equal.
990      * @param obj the object to compare against
991      * @return true if the object is equal to this.
992      * @stable ICU 2.0
993      */
994     public boolean equals(Object obj) {
995         if (obj == null) return false;
996         if (this == obj)
997             return true;
998         if (getClass() != obj.getClass())
999             return false;
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;
1008     }
1009
1010     /**
1011      * Overrides clone.
1012      * @stable ICU 2.0
1013      */
1014     public Object clone() {
1015         NumberFormat other = (NumberFormat) super.clone();
1016         return other;
1017     }
1018
1019     /**
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
1027      * @stable ICU 2.0
1028      */
1029     public boolean isGroupingUsed() {
1030         return groupingUsed;
1031     }
1032
1033     /**
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.
1038      * @stable ICU 2.0
1039      */
1040     public void setGroupingUsed(boolean newValue) {
1041         groupingUsed = newValue;
1042     }
1043
1044     /**
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
1051      * @stable ICU 2.0
1052      */
1053     public int getMaximumIntegerDigits() {
1054         return maximumIntegerDigits;
1055     }
1056
1057     /**
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
1062      * the new value.
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
1067      * @stable ICU 2.0
1068      */
1069     public void setMaximumIntegerDigits(int newValue) {
1070         maximumIntegerDigits = Math.max(0,newValue);
1071         if (minimumIntegerDigits > maximumIntegerDigits)
1072             minimumIntegerDigits = maximumIntegerDigits;
1073     }
1074
1075     /**
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
1083      * @stable ICU 2.0
1084      */
1085     public int getMinimumIntegerDigits() {
1086         return minimumIntegerDigits;
1087     }
1088
1089     /**
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
1094      * the new value.
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
1099      * @stable ICU 2.0
1100      */
1101     public void setMinimumIntegerDigits(int newValue) {
1102         minimumIntegerDigits = Math.max(0,newValue);
1103         if (minimumIntegerDigits > maximumIntegerDigits)
1104             maximumIntegerDigits = minimumIntegerDigits;
1105     }
1106
1107     /**
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
1112      * no effect.
1113      * @return the maximum number of fraction digits
1114      * @see #setMaximumFractionDigits
1115      * @stable ICU 2.0
1116      */
1117     public int getMaximumFractionDigits() {
1118         return maximumFractionDigits;
1119     }
1120
1121     /**
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
1126      * the new value.
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
1131      * @stable ICU 2.0
1132      */
1133     public void setMaximumFractionDigits(int newValue) {
1134         maximumFractionDigits = Math.max(0,newValue);
1135         if (maximumFractionDigits < minimumFractionDigits)
1136             minimumFractionDigits = maximumFractionDigits;
1137     }
1138
1139     /**
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
1147      * @stable ICU 2.0
1148      */
1149     public int getMinimumFractionDigits() {
1150         return minimumFractionDigits;
1151     }
1152
1153     /**
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
1158      * the new value.
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
1163      * @stable ICU 2.0
1164      */
1165     public void setMinimumFractionDigits(int newValue) {
1166         minimumFractionDigits = Math.max(0,newValue);
1167         if (maximumFractionDigits < minimumFractionDigits)
1168             maximumFractionDigits = minimumFractionDigits;
1169     }
1170
1171     /**
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
1176      * currency format.
1177      * @param theCurrency new currency object to use.  May be null for
1178      * some subclasses.
1179      * @stable ICU 2.6
1180      */
1181     public void setCurrency(Currency theCurrency) {
1182         currency = theCurrency;
1183     }
1184
1185     /**
1186      * Returns the <tt>Currency</tt> object used to display currency
1187      * amounts.  This may be null.
1188      * @stable ICU 2.6
1189      */
1190     public Currency getCurrency() {
1191         return currency;
1192     }
1193
1194     /**
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
1199      * @internal
1200      * @deprecated This API is ICU internal only.
1201      */
1202     protected Currency getEffectiveCurrency() {
1203         Currency c = getCurrency();
1204         if (c == null) {
1205             ULocale uloc = getLocale(ULocale.VALID_LOCALE);
1206             if (uloc == null) {
1207                 uloc = ULocale.getDefault(Category.FORMAT);
1208             }
1209             c = Currency.getInstance(uloc);
1210         }
1211         return c;
1212     }
1213
1214     /**
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)
1220      * @stable ICU 4.0
1221      */
1222     public int getRoundingMode() {
1223         throw new UnsupportedOperationException(
1224             "getRoundingMode must be implemented by the subclass implementation.");
1225     }
1226
1227     /**
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()
1234      * @stable ICU 4.0
1235      */
1236     public void setRoundingMode(int roundingMode) {
1237         throw new UnsupportedOperationException(
1238             "setRoundingMode must be implemented by the subclass implementation.");
1239     }
1240
1241
1242     /**
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,
1249      *                                   INTEGERSTYLE,
1250      *                                   ISOCURRENCYSTYLE, PLURALCURRENCYSTYLE,
1251      * @stable ICU 4.2
1252      */
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");
1257         }
1258 //          if (shim == null) {
1259 //              return createInstance(desiredLocale, choice);
1260 //          } else {
1261 //              // TODO: shims must call setLocale() on object they create
1262 //              return getShim().createInstance(desiredLocale, choice);
1263 //          }
1264         return getShim().createInstance(desiredLocale, choice);
1265     }
1266
1267     // =======================privates===============================
1268     // Hook for service
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);
1277
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();
1285             if(temp!=null){
1286                 pattern = temp;
1287             }
1288         }
1289
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);
1294         }
1295
1296         // Get the numbering system
1297         NumberingSystem ns = NumberingSystem.getInstance(desiredLocale);
1298         if ( ns == null ) {
1299             return null;
1300         }
1301
1302         NumberFormat format;
1303
1304         if ( ns != null && ns.isAlgorithmic()) {
1305             String nsDesc;
1306             String nsRuleSetGroup;
1307             String nsRuleSetName;
1308             ULocale nsLoc;
1309             int desiredRulesType = RuleBasedNumberFormat.NUMBERING_SYSTEM;
1310
1311             nsDesc = ns.getDescription();
1312             int firstSlash = nsDesc.indexOf("/");
1313             int lastSlash = nsDesc.lastIndexOf("/");
1314
1315             if ( lastSlash > firstSlash ) {
1316                String nsLocID = nsDesc.substring(0,firstSlash);
1317                nsRuleSetGroup = nsDesc.substring(firstSlash+1,lastSlash);
1318                nsRuleSetName = nsDesc.substring(lastSlash+1);
1319
1320                nsLoc = new ULocale(nsLocID);
1321                if ( nsRuleSetGroup.equals("SpelloutRules")) {
1322                    desiredRulesType = RuleBasedNumberFormat.SPELLOUT;
1323                }
1324             } else {
1325                 nsLoc = desiredLocale;
1326                 nsRuleSetName = nsDesc;
1327             }
1328
1329             RuleBasedNumberFormat r = new RuleBasedNumberFormat(nsLoc,desiredRulesType);
1330             r.setDefaultRuleSet(nsRuleSetName);
1331             format = r;
1332         } else {
1333             DecimalFormat f = new DecimalFormat(pattern, symbols, choice);
1334             // System.out.println("loc: " + desiredLocale + " choice: " + choice + " pat: " + pattern + " sym: " + symbols + " result: " + format);
1335
1336             /*Bug 4408066
1337              Add codes for the new method getIntegerInstance() [Richard/GCL]
1338             */
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);
1345             }
1346             format = f;
1347        }
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.
1350         // Revisit this.
1351         ULocale valid = symbols.getLocale(ULocale.VALID_LOCALE);
1352         ULocale actual = symbols.getLocale(ULocale.ACTUAL_LOCALE);
1353         format.setLocale(valid, actual);
1354
1355         return format;
1356     }
1357
1358     /**
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.
1364      */
1365     protected static String getPattern(Locale forLocale, int choice) {
1366         return getPattern(ULocale.forLocale(forLocale), choice);
1367     }
1368
1369     /**
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
1374      * @stable ICU 3.2
1375      */
1376     protected static String getPattern(ULocale forLocale, int choice) {
1377
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.
1382          *
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.
1386          *
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.
1393          */
1394
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]*/
1400         //    return "#E0";
1401             // return NumberFormat.getBaseStringArray("NumberPatterns")[SCIENTIFICSTYLE];
1402         //}
1403
1404         /* {dlf}
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");
1411             // Update the cache
1412             cachedLocaleData.put(forLocale, numberPatterns);
1413         }
1414         */
1415
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.
1420          */
1421         int entry = (choice == INTEGERSTYLE) ? NUMBERSTYLE :
1422                 ((choice == ISOCURRENCYSTYLE || choice == PLURALCURRENCYSTYLE)?
1423                 CURRENCYSTYLE : choice); //[Richard/GCL]
1424         
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]);
1429         //
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.
1433         //
1434     }
1435
1436     /**
1437      * First, read in the default serializable data.
1438      *
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.
1446      */
1447     private void readObject(ObjectInputStream stream)
1448          throws IOException, ClassNotFoundException
1449     {
1450         stream.defaultReadObject();
1451         ///CLOVER:OFF
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;
1459         }
1460         ///CLOVER:ON
1461         /*Bug 4185761
1462           Validate the min and max fields [Richard/GCL]
1463         */
1464         if (minimumIntegerDigits > maximumIntegerDigits ||
1465             minimumFractionDigits > maximumFractionDigits ||
1466             minimumIntegerDigits < 0 || minimumFractionDigits < 0) {
1467             throw new InvalidObjectException("Digit count range invalid");
1468         }
1469         serialVersionOnStream = currentSerialVersion;
1470     }
1471
1472     /**
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.
1478      */
1479     private void writeObject(ObjectOutputStream stream)
1480          throws IOException
1481     {
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();
1491     }
1492
1493 // Unused -- Alan 2003-05
1494 //    /**
1495 //     * Cache to hold the NumberPatterns of a Locale.
1496 //     */
1497 //    private static final Hashtable cachedLocaleData = new Hashtable(3);
1498
1499       private static final char[] doubleCurrencySign = {0xA4, 0xA4};
1500       private static final String doubleCurrencyStr = new String(doubleCurrencySign);
1501
1502     /*Bug 4408066
1503       Add Field for the new method getIntegerInstance() [Richard/GCL]
1504     */
1505
1506
1507     /**
1508      * True if the the grouping (i.e. thousands) separator is used when
1509      * formatting and parsing numbers.
1510      *
1511      * @serial
1512      * @see #isGroupingUsed
1513      */
1514     private boolean groupingUsed = true;
1515
1516     /**
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>.
1520      * <p>
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.
1528      *
1529      * @serial
1530      * @see #getMaximumIntegerDigits
1531      */
1532     private byte    maxIntegerDigits = 40;
1533
1534     /**
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>.
1538      * <p>
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.
1546      *
1547      * @serial
1548      * @see #getMinimumIntegerDigits
1549      */
1550     private byte    minIntegerDigits = 1;
1551
1552     /**
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>.
1556      * <p>
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.
1564      *
1565      * @serial
1566      * @see #getMaximumFractionDigits
1567      */
1568     private byte    maxFractionDigits = 3;    // invariant, >= minFractionDigits
1569
1570     /**
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>.
1574      * <p>
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.
1582      *
1583      * @serial
1584      * @see #getMinimumFractionDigits
1585      */
1586     private byte    minFractionDigits = 0;
1587
1588     /**
1589      * True if this format will parse numbers as integers only.
1590      *
1591      * @serial
1592      * @see #isParseIntegerOnly
1593      */
1594     private boolean parseIntegerOnly = false;
1595
1596     // new fields for 1.2.  byte is too small for integer digits.
1597
1598     /**
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>.
1602      *
1603      * @serial
1604      * @see #getMaximumIntegerDigits
1605      */
1606     private int    maximumIntegerDigits = 40;
1607
1608     /**
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>.
1612      *
1613      * @serial
1614      * @see #getMinimumIntegerDigits
1615      */
1616     private int    minimumIntegerDigits = 1;
1617
1618     /**
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>.
1622      *
1623      * @serial
1624      * @see #getMaximumFractionDigits
1625      */
1626     private int    maximumFractionDigits = 3;    // invariant, >= minFractionDigits
1627
1628     /**
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>.
1632      *
1633      * @serial
1634      * @see #getMinimumFractionDigits
1635      */
1636     private int    minimumFractionDigits = 0;
1637
1638     /**
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.
1642      * @since ICU 2.6
1643      */
1644     private Currency currency;
1645
1646     static final int currentSerialVersion = 1;
1647
1648     /**
1649      * Describes the version of <code>NumberFormat</code> present on the stream.
1650      * Possible values are:
1651      * <ul>
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.
1656      *
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>
1660      *     are used instead.
1661      * </ul>
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.
1665      *
1666      * @serial
1667      */
1668     private int serialVersionOnStream = currentSerialVersion;
1669
1670     // Removed "implements Cloneable" clause.  Needs to update serialization
1671     // ID for backward compatibility.
1672     private static final long serialVersionUID = -2308460125733713944L;
1673
1674     /**
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.
1678      * @stable ICU 2.6
1679      */
1680     public NumberFormat() {
1681     }
1682
1683     // new in ICU4J 3.6
1684     private boolean parseStrict;
1685
1686     /**
1687      * The instances of this inner class are used as attribute keys and values
1688      * in AttributedCharacterIterator that
1689      * NumberFormat.formatToCharacterIterator() method returns.
1690      * <p>
1691      * There is no public constructor to this class, the only instances are the
1692      * constants defined here.
1693      * <p>
1694      * @stable ICU 3.6
1695      */
1696     public static class Field extends Format.Field {
1697         // generated by serialver from JDK 1.4.1_01
1698         static final long serialVersionUID = -4516273749929385842L;
1699
1700         /**
1701          * @stable ICU 3.6
1702          */
1703         public static final Field SIGN = new Field("sign");
1704
1705         /**
1706          * @stable ICU 3.6
1707          */
1708         public static final Field INTEGER = new Field("integer");
1709
1710         /**
1711          * @stable ICU 3.6
1712          */
1713         public static final Field FRACTION = new Field("fraction");
1714
1715         /**
1716          * @stable ICU 3.6
1717          */
1718         public static final Field EXPONENT = new Field("exponent");
1719
1720         /**
1721          * @stable ICU 3.6
1722          */
1723         public static final Field EXPONENT_SIGN = new Field("exponent sign");
1724
1725         /**
1726          * @stable ICU 3.6
1727          */
1728         public static final Field EXPONENT_SYMBOL = new Field("exponent symbol");
1729
1730         /**
1731          * @stable ICU 3.6
1732          */
1733         public static final Field DECIMAL_SEPARATOR = new Field("decimal separator");
1734         /**
1735          * @stable ICU 3.6
1736          */
1737         public static final Field GROUPING_SEPARATOR = new Field("grouping separator");
1738
1739         /**
1740          * @stable ICU 3.6
1741          */
1742         public static final Field PERCENT = new Field("percent");
1743
1744         /**
1745          * @stable ICU 3.6
1746          */
1747         public static final Field PERMILLE = new Field("per mille");
1748
1749         /**
1750          * @stable ICU 3.6
1751          */
1752         public static final Field CURRENCY = new Field("currency");
1753
1754         /**
1755          * Constructs a new instance of NumberFormat.Field with the given field
1756          * name.
1757          * @stable ICU 3.6
1758          */
1759         protected Field(String fieldName) {
1760             super(fieldName);
1761         }
1762
1763         /**
1764          * serizalization method resolve instances to the constant
1765          * NumberFormat.Field values
1766          * @stable ICU 3.6
1767          */
1768         protected Object readResolve() throws InvalidObjectException {
1769             if (this.getName().equals(INTEGER.getName()))
1770                 return INTEGER;
1771             if (this.getName().equals(FRACTION.getName()))
1772                 return FRACTION;
1773             if (this.getName().equals(EXPONENT.getName()))
1774                 return EXPONENT;
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()))
1780                 return CURRENCY;
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()))
1786                 return PERCENT;
1787             if (this.getName().equals(PERMILLE.getName()))
1788                 return PERMILLE;
1789             if (this.getName().equals(SIGN.getName()))
1790                 return SIGN;
1791
1792             throw new InvalidObjectException("An invalid object.");
1793         }
1794     }
1795 }