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