1 /*
2 * Copyright (c) 1996, 2018, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
37 */
38
39 package java.text;
40
41 import java.io.IOException;
42 import java.io.InvalidObjectException;
43 import java.io.ObjectInputStream;
44 import java.math.BigDecimal;
45 import java.math.BigInteger;
46 import java.math.RoundingMode;
47 import java.text.spi.NumberFormatProvider;
48 import java.util.ArrayList;
49 import java.util.Currency;
50 import java.util.Locale;
51 import java.util.concurrent.atomic.AtomicInteger;
52 import java.util.concurrent.atomic.AtomicLong;
53 import sun.util.locale.provider.LocaleProviderAdapter;
54 import sun.util.locale.provider.ResourceBundleBasedAdapter;
55
56 /**
57 * <code>DecimalFormat</code> is a concrete subclass of
58 * <code>NumberFormat</code> that formats decimal numbers. It has a variety of
59 * features designed to make it possible to parse and format numbers in any
60 * locale, including support for Western, Arabic, and Indic digits. It also
61 * supports different kinds of numbers, including integers (123), fixed-point
62 * numbers (123.4), scientific notation (1.23E4), percentages (12%), and
63 * currency amounts ($123). All of these can be localized.
64 *
65 * <p>To obtain a <code>NumberFormat</code> for a specific locale, including the
66 * default locale, call one of <code>NumberFormat</code>'s factory methods, such
67 * as <code>getInstance()</code>. In general, do not call the
68 * <code>DecimalFormat</code> constructors directly, since the
69 * <code>NumberFormat</code> factory methods may return subclasses other than
70 * <code>DecimalFormat</code>. If you need to customize the format object, do
71 * something like this:
72 *
73 * <blockquote><pre>
74 * NumberFormat f = NumberFormat.getInstance(loc);
75 * if (f instanceof DecimalFormat) {
76 * ((DecimalFormat) f).setDecimalSeparatorAlwaysShown(true);
77 * }
78 * </pre></blockquote>
79 *
80 * <p>A <code>DecimalFormat</code> comprises a <em>pattern</em> and a set of
81 * <em>symbols</em>. The pattern may be set directly using
82 * <code>applyPattern()</code>, or indirectly using the API methods. The
83 * symbols are stored in a <code>DecimalFormatSymbols</code> object. When using
84 * the <code>NumberFormat</code> factory methods, the pattern and symbols are
85 * read from localized <code>ResourceBundle</code>s.
86 *
87 * <h3>Patterns</h3>
88 *
89 * <code>DecimalFormat</code> patterns have the following syntax:
90 * <blockquote><pre>
91 * <i>Pattern:</i>
92 * <i>PositivePattern</i>
93 * <i>PositivePattern</i> ; <i>NegativePattern</i>
94 * <i>PositivePattern:</i>
95 * <i>Prefix<sub>opt</sub></i> <i>Number</i> <i>Suffix<sub>opt</sub></i>
96 * <i>NegativePattern:</i>
97 * <i>Prefix<sub>opt</sub></i> <i>Number</i> <i>Suffix<sub>opt</sub></i>
98 * <i>Prefix:</i>
99 * any Unicode characters except \uFFFE, \uFFFF, and special characters
100 * <i>Suffix:</i>
101 * any Unicode characters except \uFFFE, \uFFFF, and special characters
102 * <i>Number:</i>
103 * <i>Integer</i> <i>Exponent<sub>opt</sub></i>
104 * <i>Integer</i> . <i>Fraction</i> <i>Exponent<sub>opt</sub></i>
105 * <i>Integer:</i>
106 * <i>MinimumInteger</i>
107 * #
108 * # <i>Integer</i>
109 * # , <i>Integer</i>
110 * <i>MinimumInteger:</i>
111 * 0
112 * 0 <i>MinimumInteger</i>
113 * 0 , <i>MinimumInteger</i>
114 * <i>Fraction:</i>
115 * <i>MinimumFraction<sub>opt</sub></i> <i>OptionalFraction<sub>opt</sub></i>
116 * <i>MinimumFraction:</i>
117 * 0 <i>MinimumFraction<sub>opt</sub></i>
118 * <i>OptionalFraction:</i>
119 * # <i>OptionalFraction<sub>opt</sub></i>
120 * <i>Exponent:</i>
121 * E <i>MinimumExponent</i>
122 * <i>MinimumExponent:</i>
123 * 0 <i>MinimumExponent<sub>opt</sub></i>
124 * </pre></blockquote>
125 *
126 * <p>A <code>DecimalFormat</code> pattern contains a positive and negative
127 * subpattern, for example, <code>"#,##0.00;(#,##0.00)"</code>. Each
128 * subpattern has a prefix, numeric part, and suffix. The negative subpattern
129 * is optional; if absent, then the positive subpattern prefixed with the
130 * localized minus sign (<code>'-'</code> in most locales) is used as the
131 * negative subpattern. That is, <code>"0.00"</code> alone is equivalent to
132 * <code>"0.00;-0.00"</code>. If there is an explicit negative subpattern, it
133 * serves only to specify the negative prefix and suffix; the number of digits,
134 * minimal digits, and other characteristics are all the same as the positive
135 * pattern. That means that <code>"#,##0.0#;(#)"</code> produces precisely
136 * the same behavior as <code>"#,##0.0#;(#,##0.0#)"</code>.
137 *
138 * <p>The prefixes, suffixes, and various symbols used for infinity, digits,
139 * thousands separators, decimal separators, etc. may be set to arbitrary
140 * values, and they will appear properly during formatting. However, care must
141 * be taken that the symbols and strings do not conflict, or parsing will be
142 * unreliable. For example, either the positive and negative prefixes or the
143 * suffixes must be distinct for <code>DecimalFormat.parse()</code> to be able
144 * to distinguish positive from negative values. (If they are identical, then
145 * <code>DecimalFormat</code> will behave as if no negative subpattern was
146 * specified.) Another example is that the decimal separator and thousands
147 * separator should be distinct characters, or parsing will be impossible.
148 *
149 * <p>The grouping separator is commonly used for thousands, but in some
150 * countries it separates ten-thousands. The grouping size is a constant number
151 * of digits between the grouping characters, such as 3 for 100,000,000 or 4 for
152 * 1,0000,0000. If you supply a pattern with multiple grouping characters, the
153 * interval between the last one and the end of the integer is the one that is
154 * used. So <code>"#,##,###,####"</code> == <code>"######,####"</code> ==
155 * <code>"##,####,####"</code>.
156 *
157 * <h4><a id="special_pattern_character">Special Pattern Characters</a></h4>
158 *
159 * <p>Many characters in a pattern are taken literally; they are matched during
160 * parsing and output unchanged during formatting. Special characters, on the
161 * other hand, stand for other characters, strings, or classes of characters.
162 * They must be quoted, unless noted otherwise, if they are to appear in the
163 * prefix or suffix as literals.
164 *
165 * <p>The characters listed here are used in non-localized patterns. Localized
166 * patterns use the corresponding characters taken from this formatter's
167 * <code>DecimalFormatSymbols</code> object instead, and these characters lose
168 * their special status. Two exceptions are the currency sign and quote, which
169 * are not localized.
170 *
171 * <blockquote>
172 * <table class="striped">
173 * <caption style="display:none">Chart showing symbol, location, localized, and meaning.</caption>
174 * <thead>
175 * <tr>
176 * <th scope="col" style="text-align:left">Symbol
177 * <th scope="col" style="text-align:left">Location
178 * <th scope="col" style="text-align:left">Localized?
179 * <th scope="col" style="text-align:left">Meaning
180 * </thead>
181 * <tbody>
182 * <tr style="vertical-align:top">
183 * <th scope="row"><code>0</code>
184 * <td>Number
185 * <td>Yes
186 * <td>Digit
187 * <tr style="vertical-align: top">
188 * <th scope="row"><code>#</code>
189 * <td>Number
190 * <td>Yes
191 * <td>Digit, zero shows as absent
192 * <tr style="vertical-align:top">
193 * <th scope="row"><code>.</code>
194 * <td>Number
195 * <td>Yes
196 * <td>Decimal separator or monetary decimal separator
197 * <tr style="vertical-align: top">
198 * <th scope="row"><code>-</code>
199 * <td>Number
200 * <td>Yes
201 * <td>Minus sign
202 * <tr style="vertical-align:top">
203 * <th scope="row"><code>,</code>
204 * <td>Number
205 * <td>Yes
206 * <td>Grouping separator
207 * <tr style="vertical-align: top">
208 * <th scope="row"><code>E</code>
209 * <td>Number
210 * <td>Yes
211 * <td>Separates mantissa and exponent in scientific notation.
212 * <em>Need not be quoted in prefix or suffix.</em>
213 * <tr style="vertical-align:top">
214 * <th scope="row"><code>;</code>
215 * <td>Subpattern boundary
216 * <td>Yes
217 * <td>Separates positive and negative subpatterns
218 * <tr style="vertical-align: top">
219 * <th scope="row"><code>%</code>
220 * <td>Prefix or suffix
221 * <td>Yes
222 * <td>Multiply by 100 and show as percentage
223 * <tr style="vertical-align:top">
224 * <th scope="row"><code>\u2030</code>
225 * <td>Prefix or suffix
226 * <td>Yes
227 * <td>Multiply by 1000 and show as per mille value
228 * <tr style="vertical-align: top">
229 * <th scope="row"><code>¤</code> (<code>\u00A4</code>)
230 * <td>Prefix or suffix
231 * <td>No
232 * <td>Currency sign, replaced by currency symbol. If
233 * doubled, replaced by international currency symbol.
234 * If present in a pattern, the monetary decimal separator
235 * is used instead of the decimal separator.
236 * <tr style="vertical-align:top">
237 * <th scope="row"><code>'</code>
238 * <td>Prefix or suffix
239 * <td>No
240 * <td>Used to quote special characters in a prefix or suffix,
241 * for example, <code>"'#'#"</code> formats 123 to
242 * <code>"#123"</code>. To create a single quote
243 * itself, use two in a row: <code>"# o''clock"</code>.
244 * </tbody>
245 * </table>
246 * </blockquote>
247 *
248 * <h4>Scientific Notation</h4>
249 *
250 * <p>Numbers in scientific notation are expressed as the product of a mantissa
251 * and a power of ten, for example, 1234 can be expressed as 1.234 x 10^3. The
252 * mantissa is often in the range 1.0 ≤ x {@literal <} 10.0, but it need not
253 * be.
254 * <code>DecimalFormat</code> can be instructed to format and parse scientific
255 * notation <em>only via a pattern</em>; there is currently no factory method
256 * that creates a scientific notation format. In a pattern, the exponent
257 * character immediately followed by one or more digit characters indicates
258 * scientific notation. Example: <code>"0.###E0"</code> formats the number
259 * 1234 as <code>"1.234E3"</code>.
260 *
261 * <ul>
262 * <li>The number of digit characters after the exponent character gives the
263 * minimum exponent digit count. There is no maximum. Negative exponents are
264 * formatted using the localized minus sign, <em>not</em> the prefix and suffix
265 * from the pattern. This allows patterns such as <code>"0.###E0 m/s"</code>.
266 *
267 * <li>The minimum and maximum number of integer digits are interpreted
268 * together:
269 *
270 * <ul>
271 * <li>If the maximum number of integer digits is greater than their minimum number
272 * and greater than 1, it forces the exponent to be a multiple of the maximum
273 * number of integer digits, and the minimum number of integer digits to be
274 * interpreted as 1. The most common use of this is to generate
275 * <em>engineering notation</em>, in which the exponent is a multiple of three,
276 * e.g., <code>"##0.#####E0"</code>. Using this pattern, the number 12345
277 * formats to <code>"12.345E3"</code>, and 123456 formats to
278 * <code>"123.456E3"</code>.
279 *
280 * <li>Otherwise, the minimum number of integer digits is achieved by adjusting the
281 * exponent. Example: 0.00123 formatted with <code>"00.###E0"</code> yields
282 * <code>"12.3E-4"</code>.
283 * </ul>
284 *
285 * <li>The number of significant digits in the mantissa is the sum of the
286 * <em>minimum integer</em> and <em>maximum fraction</em> digits, and is
287 * unaffected by the maximum integer digits. For example, 12345 formatted with
288 * <code>"##0.##E0"</code> is <code>"12.3E3"</code>. To show all digits, set
289 * the significant digits count to zero. The number of significant digits
290 * does not affect parsing.
291 *
292 * <li>Exponential patterns may not contain grouping separators.
293 * </ul>
294 *
295 * <h4>Rounding</h4>
296 *
297 * <code>DecimalFormat</code> provides rounding modes defined in
298 * {@link java.math.RoundingMode} for formatting. By default, it uses
299 * {@link java.math.RoundingMode#HALF_EVEN RoundingMode.HALF_EVEN}.
300 *
301 * <h4>Digits</h4>
302 *
303 * For formatting, <code>DecimalFormat</code> uses the ten consecutive
304 * characters starting with the localized zero digit defined in the
305 * <code>DecimalFormatSymbols</code> object as digits. For parsing, these
306 * digits as well as all Unicode decimal digits, as defined by
307 * {@link Character#digit Character.digit}, are recognized.
308 *
309 * <h4>Special Values</h4>
310 *
311 * <p><code>NaN</code> is formatted as a string, which typically has a single character
312 * <code>\uFFFD</code>. This string is determined by the
313 * <code>DecimalFormatSymbols</code> object. This is the only value for which
314 * the prefixes and suffixes are not used.
315 *
316 * <p>Infinity is formatted as a string, which typically has a single character
317 * <code>\u221E</code>, with the positive or negative prefixes and suffixes
318 * applied. The infinity string is determined by the
319 * <code>DecimalFormatSymbols</code> object.
320 *
321 * <p>Negative zero (<code>"-0"</code>) parses to
322 * <ul>
323 * <li><code>BigDecimal(0)</code> if <code>isParseBigDecimal()</code> is
324 * true,
325 * <li><code>Long(0)</code> if <code>isParseBigDecimal()</code> is false
326 * and <code>isParseIntegerOnly()</code> is true,
327 * <li><code>Double(-0.0)</code> if both <code>isParseBigDecimal()</code>
328 * and <code>isParseIntegerOnly()</code> are false.
329 * </ul>
330 *
331 * <h4><a id="synchronization">Synchronization</a></h4>
332 *
333 * <p>
334 * Decimal formats are generally not synchronized.
335 * It is recommended to create separate format instances for each thread.
336 * If multiple threads access a format concurrently, it must be synchronized
337 * externally.
338 *
339 * <h4>Example</h4>
340 *
341 * <blockquote><pre>{@code
342 * <strong>// Print out a number using the localized number, integer, currency,
343 * // and percent format for each locale</strong>
344 * Locale[] locales = NumberFormat.getAvailableLocales();
345 * double myNumber = -1234.56;
346 * NumberFormat form;
347 * for (int j = 0; j < 4; ++j) {
348 * System.out.println("FORMAT");
408 String[] all = adapter.getLocaleResources(def).getNumberPatterns();
409
410 // Always applyPattern after the symbols are set
411 this.symbols = DecimalFormatSymbols.getInstance(def);
412 applyPattern(all[0], false);
413 }
414
415
416 /**
417 * Creates a DecimalFormat using the given pattern and the symbols
418 * for the default {@link java.util.Locale.Category#FORMAT FORMAT} locale.
419 * This is a convenient way to obtain a
420 * DecimalFormat when internationalization is not the main concern.
421 * <p>
422 * To obtain standard formats for a given locale, use the factory methods
423 * on NumberFormat such as getNumberInstance. These factories will
424 * return the most appropriate sub-class of NumberFormat for a given
425 * locale.
426 *
427 * @param pattern a non-localized pattern string.
428 * @exception NullPointerException if <code>pattern</code> is null
429 * @exception IllegalArgumentException if the given pattern is invalid.
430 * @see java.text.NumberFormat#getInstance
431 * @see java.text.NumberFormat#getNumberInstance
432 * @see java.text.NumberFormat#getCurrencyInstance
433 * @see java.text.NumberFormat#getPercentInstance
434 */
435 public DecimalFormat(String pattern) {
436 // Always applyPattern after the symbols are set
437 this.symbols = DecimalFormatSymbols.getInstance(Locale.getDefault(Locale.Category.FORMAT));
438 applyPattern(pattern, false);
439 }
440
441
442 /**
443 * Creates a DecimalFormat using the given pattern and symbols.
444 * Use this constructor when you need to completely customize the
445 * behavior of the format.
446 * <p>
447 * To obtain standard formats for a given
448 * locale, use the factory methods on NumberFormat such as
458 * @see java.text.NumberFormat#getNumberInstance
459 * @see java.text.NumberFormat#getCurrencyInstance
460 * @see java.text.NumberFormat#getPercentInstance
461 * @see java.text.DecimalFormatSymbols
462 */
463 public DecimalFormat (String pattern, DecimalFormatSymbols symbols) {
464 // Always applyPattern after the symbols are set
465 this.symbols = (DecimalFormatSymbols)symbols.clone();
466 applyPattern(pattern, false);
467 }
468
469
470 // Overrides
471 /**
472 * Formats a number and appends the resulting text to the given string
473 * buffer.
474 * The number can be of any subclass of {@link java.lang.Number}.
475 * <p>
476 * This implementation uses the maximum precision permitted.
477 * @param number the number to format
478 * @param toAppendTo the <code>StringBuffer</code> to which the formatted
479 * text is to be appended
480 * @param pos keeps track on the position of the field within the
481 * returned string. For example, for formatting a number
482 * {@code 1234567.89} in {@code Locale.US} locale,
483 * if the given {@code fieldPosition} is
484 * {@link NumberFormat#INTEGER_FIELD}, the begin index
485 * and end index of {@code fieldPosition} will be set
486 * to 0 and 9, respectively for the output string
487 * {@code 1,234,567.89}.
488 * @return the value passed in as <code>toAppendTo</code>
489 * @exception IllegalArgumentException if <code>number</code> is
490 * null or not an instance of <code>Number</code>.
491 * @exception NullPointerException if <code>toAppendTo</code> or
492 * <code>pos</code> is null
493 * @exception ArithmeticException if rounding is needed with rounding
494 * mode being set to RoundingMode.UNNECESSARY
495 * @see java.text.FieldPosition
496 */
497 @Override
498 public final StringBuffer format(Object number,
499 StringBuffer toAppendTo,
500 FieldPosition pos) {
501 if (number instanceof Long || number instanceof Integer ||
502 number instanceof Short || number instanceof Byte ||
503 number instanceof AtomicInteger ||
504 number instanceof AtomicLong ||
505 (number instanceof BigInteger &&
506 ((BigInteger)number).bitLength () < 64)) {
507 return format(((Number)number).longValue(), toAppendTo, pos);
508 } else if (number instanceof BigDecimal) {
509 return format((BigDecimal)number, toAppendTo, pos);
510 } else if (number instanceof BigInteger) {
511 return format((BigInteger)number, toAppendTo, pos);
512 } else if (number instanceof Number) {
897 } else {
898 maxIntDigits = getMaximumIntegerDigits();
899 minIntDigits = getMinimumIntegerDigits();
900 maxFraDigits = getMaximumFractionDigits();
901 minFraDigits = getMinimumFractionDigits();
902 maximumDigits = maxIntDigits + maxFraDigits;
903 if (maximumDigits < 0) {
904 maximumDigits = Integer.MAX_VALUE;
905 }
906 }
907
908 digitList.set(isNegative, number,
909 useExponentialNotation ? maximumDigits : 0);
910
911 return subformat(result, delegate, isNegative, true,
912 maxIntDigits, minIntDigits, maxFraDigits, minFraDigits);
913 }
914 }
915
916 /**
917 * Formats an Object producing an <code>AttributedCharacterIterator</code>.
918 * You can use the returned <code>AttributedCharacterIterator</code>
919 * to build the resulting String, as well as to determine information
920 * about the resulting String.
921 * <p>
922 * Each attribute key of the AttributedCharacterIterator will be of type
923 * <code>NumberFormat.Field</code>, with the attribute value being the
924 * same as the attribute key.
925 *
926 * @exception NullPointerException if obj is null.
927 * @exception IllegalArgumentException when the Format cannot format the
928 * given object.
929 * @exception ArithmeticException if rounding is needed with rounding
930 * mode being set to RoundingMode.UNNECESSARY
931 * @param obj The object to format
932 * @return AttributedCharacterIterator describing the formatted value.
933 * @since 1.4
934 */
935 @Override
936 public AttributedCharacterIterator formatToCharacterIterator(Object obj) {
937 CharacterIteratorFieldDelegate delegate =
938 new CharacterIteratorFieldDelegate();
939 StringBuffer sb = new StringBuffer();
940
941 if (obj instanceof Double || obj instanceof Float) {
942 format(((Number)obj).doubleValue(), sb, delegate);
943 } else if (obj instanceof Long || obj instanceof Integer ||
1899 // digits, since truncating the exponent would result in an
1900 // unacceptable inaccuracy.
1901 int fieldStart = result.length();
1902
1903 result.append(symbols.getExponentSeparator());
1904
1905 delegate.formatted(Field.EXPONENT_SYMBOL, Field.EXPONENT_SYMBOL,
1906 fieldStart, result.length(), result);
1907
1908 // For zero values, we force the exponent to zero. We
1909 // must do this here, and not earlier, because the value
1910 // is used to determine integer digit count above.
1911 if (digitList.isZero()) {
1912 exponent = 0;
1913 }
1914
1915 boolean negativeExponent = exponent < 0;
1916 if (negativeExponent) {
1917 exponent = -exponent;
1918 fieldStart = result.length();
1919 result.append(symbols.getMinusSign());
1920 delegate.formatted(Field.EXPONENT_SIGN, Field.EXPONENT_SIGN,
1921 fieldStart, result.length(), result);
1922 }
1923 digitList.set(negativeExponent, exponent);
1924
1925 int eFieldStart = result.length();
1926
1927 for (int i=digitList.decimalAt; i<minExponentDigits; ++i) {
1928 result.append(zero);
1929 }
1930 for (int i=0; i<digitList.decimalAt; ++i) {
1931 result.append((i < digitList.count) ?
1932 (char)(digitList.digits[i] + zeroDelta) : zero);
1933 }
1934 delegate.formatted(Field.EXPONENT, Field.EXPONENT, eFieldStart,
1935 result.length(), result);
1936 } else {
1937 int iFieldStart = result.length();
1938
1939 // Output the integer portion. Here 'count' is the total
2025 result.append(zero);
2026 continue;
2027 }
2028
2029 // Output a digit, if we have any precision left, or a
2030 // zero if we don't. We don't want to output noise digits.
2031 if (!isInteger && digitIndex < digitList.count) {
2032 result.append((char)(digitList.digits[digitIndex++] + zeroDelta));
2033 } else {
2034 result.append(zero);
2035 }
2036 }
2037
2038 // Record field information for caller.
2039 delegate.formatted(FRACTION_FIELD, Field.FRACTION, Field.FRACTION,
2040 fFieldStart, result.length(), result);
2041 }
2042 }
2043
2044 /**
2045 * Appends the String <code>string</code> to <code>result</code>.
2046 * <code>delegate</code> is notified of all the
2047 * <code>FieldPosition</code>s in <code>positions</code>.
2048 * <p>
2049 * If one of the <code>FieldPosition</code>s in <code>positions</code>
2050 * identifies a <code>SIGN</code> attribute, it is mapped to
2051 * <code>signAttribute</code>. This is used
2052 * to map the <code>SIGN</code> attribute to the <code>EXPONENT</code>
2053 * attribute as necessary.
2054 * <p>
2055 * This is used by <code>subformat</code> to add the prefix/suffix.
2056 */
2057 private void append(StringBuffer result, String string,
2058 FieldDelegate delegate,
2059 FieldPosition[] positions,
2060 Format.Field signAttribute) {
2061 int start = result.length();
2062
2063 if (!string.isEmpty()) {
2064 result.append(string);
2065 for (int counter = 0, max = positions.length; counter < max;
2066 counter++) {
2067 FieldPosition fp = positions[counter];
2068 Format.Field attribute = fp.getFieldAttribute();
2069
2070 if (attribute == Field.SIGN) {
2071 attribute = signAttribute;
2072 }
2073 delegate.formatted(attribute, attribute,
2074 start + fp.getBeginIndex(),
2075 start + fp.getEndIndex(), result);
2076 }
2077 }
2078 }
2079
2080 /**
2081 * Parses text from a string to produce a <code>Number</code>.
2082 * <p>
2083 * The method attempts to parse text starting at the index given by
2084 * <code>pos</code>.
2085 * If parsing succeeds, then the index of <code>pos</code> is updated
2086 * to the index after the last character used (parsing does not necessarily
2087 * use all characters up to the end of the string), and the parsed
2088 * number is returned. The updated <code>pos</code> can be used to
2089 * indicate the starting point for the next call to this method.
2090 * If an error occurs, then the index of <code>pos</code> is not
2091 * changed, the error index of <code>pos</code> is set to the index of
2092 * the character where the error occurred, and null is returned.
2093 * <p>
2094 * The subclass returned depends on the value of {@link #isParseBigDecimal}
2095 * as well as on the string being parsed.
2096 * <ul>
2097 * <li>If <code>isParseBigDecimal()</code> is false (the default),
2098 * most integer values are returned as <code>Long</code>
2099 * objects, no matter how they are written: <code>"17"</code> and
2100 * <code>"17.000"</code> both parse to <code>Long(17)</code>.
2101 * Values that cannot fit into a <code>Long</code> are returned as
2102 * <code>Double</code>s. This includes values with a fractional part,
2103 * infinite values, <code>NaN</code>, and the value -0.0.
2104 * <code>DecimalFormat</code> does <em>not</em> decide whether to
2105 * return a <code>Double</code> or a <code>Long</code> based on the
2106 * presence of a decimal separator in the source string. Doing so
2107 * would prevent integers that overflow the mantissa of a double,
2108 * such as <code>"-9,223,372,036,854,775,808.00"</code>, from being
2109 * parsed accurately.
2110 * <p>
2111 * Callers may use the <code>Number</code> methods
2112 * <code>doubleValue</code>, <code>longValue</code>, etc., to obtain
2113 * the type they want.
2114 * <li>If <code>isParseBigDecimal()</code> is true, values are returned
2115 * as <code>BigDecimal</code> objects. The values are the ones
2116 * constructed by {@link java.math.BigDecimal#BigDecimal(String)}
2117 * for corresponding strings in locale-independent format. The
2118 * special cases negative and positive infinity and NaN are returned
2119 * as <code>Double</code> instances holding the values of the
2120 * corresponding <code>Double</code> constants.
2121 * </ul>
2122 * <p>
2123 * <code>DecimalFormat</code> parses all Unicode characters that represent
2124 * decimal digits, as defined by <code>Character.digit()</code>. In
2125 * addition, <code>DecimalFormat</code> also recognizes as digits the ten
2126 * consecutive characters starting with the localized zero digit defined in
2127 * the <code>DecimalFormatSymbols</code> object.
2128 *
2129 * @param text the string to be parsed
2130 * @param pos A <code>ParsePosition</code> object with index and error
2131 * index information as described above.
2132 * @return the parsed value, or <code>null</code> if the parse fails
2133 * @exception NullPointerException if <code>text</code> or
2134 * <code>pos</code> is null.
2135 */
2136 @Override
2137 public Number parse(String text, ParsePosition pos) {
2138 // special case NaN
2139 if (text.regionMatches(pos.index, symbols.getNaN(), 0, symbols.getNaN().length())) {
2140 pos.index = pos.index + symbols.getNaN().length();
2141 return Double.valueOf(Double.NaN);
2142 }
2143
2144 boolean[] status = new boolean[STATUS_LENGTH];
2145 if (!subparse(text, pos, positivePrefix, negativePrefix, digitList, false, status)) {
2146 return null;
2147 }
2148
2149 // special case INFINITY
2150 if (status[STATUS_INFINITE]) {
2151 if (status[STATUS_POSITIVE] == (multiplier >= 0)) {
2152 return Double.valueOf(Double.POSITIVE_INFINITY);
2153 } else {
2154 return Double.valueOf(Double.NEGATIVE_INFINITY);
2458 if (isParseIntegerOnly() || sawDecimal) {
2459 break;
2460 }
2461 digits.decimalAt = digitCount; // Not digits.count!
2462 sawDecimal = true;
2463 } else if (!isExponent && ch == grouping && isGroupingUsed()) {
2464 if (sawDecimal) {
2465 break;
2466 }
2467 // Ignore grouping characters, if we are using them, but
2468 // require that they be followed by a digit. Otherwise
2469 // we backup and reprocess them.
2470 backup = position;
2471 } else if (checkExponent && !isExponent && text.regionMatches(position, exponentString, 0, exponentString.length())
2472 && !sawExponent) {
2473 // Process the exponent by recursively calling this method.
2474 ParsePosition pos = new ParsePosition(position + exponentString.length());
2475 boolean[] stat = new boolean[STATUS_LENGTH];
2476 DigitList exponentDigits = new DigitList();
2477
2478 if (subparse(text, pos, "", Character.toString(symbols.getMinusSign()), exponentDigits, true, stat) &&
2479 exponentDigits.fitsIntoLong(stat[STATUS_POSITIVE], true)) {
2480 position = pos.index; // Advance past the exponent
2481 exponent = (int)exponentDigits.getLong();
2482 if (!stat[STATUS_POSITIVE]) {
2483 exponent = -exponent;
2484 }
2485 sawExponent = true;
2486 }
2487 break; // Whether we fail or succeed, we exit this loop
2488 } else {
2489 break;
2490 }
2491 }
2492
2493 if (backup != -1) {
2494 position = backup;
2495 }
2496
2497 // If there was no decimal point we have an integer
2498 if (!sawDecimal) {
2556 public String getPositivePrefix () {
2557 return positivePrefix;
2558 }
2559
2560 /**
2561 * Set the positive prefix.
2562 * <P>Examples: +123, $123, sFr123
2563 *
2564 * @param newValue the new positive prefix
2565 */
2566 public void setPositivePrefix (String newValue) {
2567 positivePrefix = newValue;
2568 posPrefixPattern = null;
2569 positivePrefixFieldPositions = null;
2570 fastPathCheckNeeded = true;
2571 }
2572
2573 /**
2574 * Returns the FieldPositions of the fields in the prefix used for
2575 * positive numbers. This is not used if the user has explicitly set
2576 * a positive prefix via <code>setPositivePrefix</code>. This is
2577 * lazily created.
2578 *
2579 * @return FieldPositions in positive prefix
2580 */
2581 private FieldPosition[] getPositivePrefixFieldPositions() {
2582 if (positivePrefixFieldPositions == null) {
2583 if (posPrefixPattern != null) {
2584 positivePrefixFieldPositions = expandAffix(posPrefixPattern);
2585 } else {
2586 positivePrefixFieldPositions = EmptyFieldPositionArray;
2587 }
2588 }
2589 return positivePrefixFieldPositions;
2590 }
2591
2592 /**
2593 * Get the negative prefix.
2594 * <P>Examples: -123, ($123) (with negative suffix), sFr-123
2595 *
2596 * @return the negative prefix
2597 */
2598 public String getNegativePrefix () {
2599 return negativePrefix;
2600 }
2601
2602 /**
2603 * Set the negative prefix.
2604 * <P>Examples: -123, ($123) (with negative suffix), sFr-123
2605 *
2606 * @param newValue the new negative prefix
2607 */
2608 public void setNegativePrefix (String newValue) {
2609 negativePrefix = newValue;
2610 negPrefixPattern = null;
2611 fastPathCheckNeeded = true;
2612 }
2613
2614 /**
2615 * Returns the FieldPositions of the fields in the prefix used for
2616 * negative numbers. This is not used if the user has explicitly set
2617 * a negative prefix via <code>setNegativePrefix</code>. This is
2618 * lazily created.
2619 *
2620 * @return FieldPositions in positive prefix
2621 */
2622 private FieldPosition[] getNegativePrefixFieldPositions() {
2623 if (negativePrefixFieldPositions == null) {
2624 if (negPrefixPattern != null) {
2625 negativePrefixFieldPositions = expandAffix(negPrefixPattern);
2626 } else {
2627 negativePrefixFieldPositions = EmptyFieldPositionArray;
2628 }
2629 }
2630 return negativePrefixFieldPositions;
2631 }
2632
2633 /**
2634 * Get the positive suffix.
2635 * <P>Example: 123%
2636 *
2637 * @return the positive suffix
2638 */
2639 public String getPositiveSuffix () {
2640 return positiveSuffix;
2641 }
2642
2643 /**
2644 * Set the positive suffix.
2645 * <P>Example: 123%
2646 *
2647 * @param newValue the new positive suffix
2648 */
2649 public void setPositiveSuffix (String newValue) {
2650 positiveSuffix = newValue;
2651 posSuffixPattern = null;
2652 fastPathCheckNeeded = true;
2653 }
2654
2655 /**
2656 * Returns the FieldPositions of the fields in the suffix used for
2657 * positive numbers. This is not used if the user has explicitly set
2658 * a positive suffix via <code>setPositiveSuffix</code>. This is
2659 * lazily created.
2660 *
2661 * @return FieldPositions in positive prefix
2662 */
2663 private FieldPosition[] getPositiveSuffixFieldPositions() {
2664 if (positiveSuffixFieldPositions == null) {
2665 if (posSuffixPattern != null) {
2666 positiveSuffixFieldPositions = expandAffix(posSuffixPattern);
2667 } else {
2668 positiveSuffixFieldPositions = EmptyFieldPositionArray;
2669 }
2670 }
2671 return positiveSuffixFieldPositions;
2672 }
2673
2674 /**
2675 * Get the negative suffix.
2676 * <P>Examples: -123%, ($123) (with positive suffixes)
2677 *
2678 * @return the negative suffix
2679 */
2680 public String getNegativeSuffix () {
2681 return negativeSuffix;
2682 }
2683
2684 /**
2685 * Set the negative suffix.
2686 * <P>Examples: 123%
2687 *
2688 * @param newValue the new negative suffix
2689 */
2690 public void setNegativeSuffix (String newValue) {
2691 negativeSuffix = newValue;
2692 negSuffixPattern = null;
2693 fastPathCheckNeeded = true;
2694 }
2695
2696 /**
2697 * Returns the FieldPositions of the fields in the suffix used for
2698 * negative numbers. This is not used if the user has explicitly set
2699 * a negative suffix via <code>setNegativeSuffix</code>. This is
2700 * lazily created.
2701 *
2702 * @return FieldPositions in positive prefix
2703 */
2704 private FieldPosition[] getNegativeSuffixFieldPositions() {
2705 if (negativeSuffixFieldPositions == null) {
2706 if (negSuffixPattern != null) {
2707 negativeSuffixFieldPositions = expandAffix(negSuffixPattern);
2708 } else {
2709 negativeSuffixFieldPositions = EmptyFieldPositionArray;
2710 }
2711 }
2712 return negativeSuffixFieldPositions;
2713 }
2714
2715 /**
2716 * Gets the multiplier for use in percent, per mille, and similar
2717 * formats.
2718 *
2719 * @return the multiplier
2794 */
2795 public boolean isDecimalSeparatorAlwaysShown() {
2796 return decimalSeparatorAlwaysShown;
2797 }
2798
2799 /**
2800 * Allows you to set the behavior of the decimal separator with integers.
2801 * (The decimal separator will always appear with decimals.)
2802 * <P>Example: Decimal ON: 12345 → 12345.; OFF: 12345 → 12345
2803 *
2804 * @param newValue {@code true} if the decimal separator is always shown;
2805 * {@code false} otherwise
2806 */
2807 public void setDecimalSeparatorAlwaysShown(boolean newValue) {
2808 decimalSeparatorAlwaysShown = newValue;
2809 fastPathCheckNeeded = true;
2810 }
2811
2812 /**
2813 * Returns whether the {@link #parse(java.lang.String, java.text.ParsePosition)}
2814 * method returns <code>BigDecimal</code>. The default value is false.
2815 *
2816 * @return {@code true} if the parse method returns BigDecimal;
2817 * {@code false} otherwise
2818 * @see #setParseBigDecimal
2819 * @since 1.5
2820 */
2821 public boolean isParseBigDecimal() {
2822 return parseBigDecimal;
2823 }
2824
2825 /**
2826 * Sets whether the {@link #parse(java.lang.String, java.text.ParsePosition)}
2827 * method returns <code>BigDecimal</code>.
2828 *
2829 * @param newValue {@code true} if the parse method returns BigDecimal;
2830 * {@code false} otherwise
2831 * @see #isParseBigDecimal
2832 * @since 1.5
2833 */
2834 public void setParseBigDecimal(boolean newValue) {
2835 parseBigDecimal = newValue;
2836 }
2837
2838 /**
2839 * Standard override; no change in semantics.
2840 */
2841 @Override
2842 public Object clone() {
2843 DecimalFormat other = (DecimalFormat) super.clone();
2844 other.symbols = (DecimalFormatSymbols) symbols.clone();
2845 other.digitList = (DigitList) digitList.clone();
2846
2847 // Fast-path is almost stateless algorithm. The only logical state is the
2974 * @param buffer a scratch StringBuffer; its contents will be lost
2975 * @return the expanded equivalent of pattern
2976 */
2977 private String expandAffix(String pattern, StringBuffer buffer) {
2978 buffer.setLength(0);
2979 for (int i=0; i<pattern.length(); ) {
2980 char c = pattern.charAt(i++);
2981 if (c == QUOTE) {
2982 c = pattern.charAt(i++);
2983 switch (c) {
2984 case CURRENCY_SIGN:
2985 if (i<pattern.length() &&
2986 pattern.charAt(i) == CURRENCY_SIGN) {
2987 ++i;
2988 buffer.append(symbols.getInternationalCurrencySymbol());
2989 } else {
2990 buffer.append(symbols.getCurrencySymbol());
2991 }
2992 continue;
2993 case PATTERN_PERCENT:
2994 c = symbols.getPercent();
2995 break;
2996 case PATTERN_PER_MILLE:
2997 c = symbols.getPerMill();
2998 break;
2999 case PATTERN_MINUS:
3000 c = symbols.getMinusSign();
3001 break;
3002 }
3003 }
3004 buffer.append(c);
3005 }
3006 return buffer.toString();
3007 }
3008
3009 /**
3010 * Expand an affix pattern into an array of FieldPositions describing
3011 * how the pattern would be expanded.
3012 * All characters in the
3013 * pattern are literal unless prefixed by QUOTE. The following characters
3014 * after QUOTE are recognized: PATTERN_PERCENT, PATTERN_PER_MILLE,
3015 * PATTERN_MINUS, and CURRENCY_SIGN. If CURRENCY_SIGN is doubled (QUOTE +
3016 * CURRENCY_SIGN + CURRENCY_SIGN), it is interpreted as an ISO 4217
3017 * currency code. Any other character after a QUOTE represents itself.
3018 * QUOTE must be followed by another character; QUOTE may not occur by
3019 * itself at the end of the pattern.
3020 *
3021 * @param pattern the non-null, possibly empty pattern
3022 * @return FieldPosition array of the resulting fields.
3023 */
3024 private FieldPosition[] expandAffix(String pattern) {
3025 ArrayList<FieldPosition> positions = null;
3026 int stringIndex = 0;
3027 for (int i=0; i<pattern.length(); ) {
3028 char c = pattern.charAt(i++);
3029 if (c == QUOTE) {
3030 int field = -1;
3031 Format.Field fieldID = null;
3032 c = pattern.charAt(i++);
3033 switch (c) {
3034 case CURRENCY_SIGN:
3035 String string;
3036 if (i<pattern.length() &&
3037 pattern.charAt(i) == CURRENCY_SIGN) {
3038 ++i;
3039 string = symbols.getInternationalCurrencySymbol();
3040 } else {
3041 string = symbols.getCurrencySymbol();
3042 }
3043 if (!string.isEmpty()) {
3044 if (positions == null) {
3045 positions = new ArrayList<>(2);
3046 }
3047 FieldPosition fp = new FieldPosition(Field.CURRENCY);
3048 fp.setBeginIndex(stringIndex);
3049 fp.setEndIndex(stringIndex + string.length());
3050 positions.add(fp);
3051 stringIndex += string.length();
3052 }
3053 continue;
3054 case PATTERN_PERCENT:
3055 c = symbols.getPercent();
3056 field = -1;
3057 fieldID = Field.PERCENT;
3058 break;
3059 case PATTERN_PER_MILLE:
3060 c = symbols.getPerMill();
3061 field = -1;
3062 fieldID = Field.PERMILLE;
3063 break;
3064 case PATTERN_MINUS:
3065 c = symbols.getMinusSign();
3066 field = -1;
3067 fieldID = Field.SIGN;
3068 break;
3069 }
3070 if (fieldID != null) {
3071 if (positions == null) {
3072 positions = new ArrayList<>(2);
3073 }
3074 FieldPosition fp = new FieldPosition(fieldID, field);
3075 fp.setBeginIndex(stringIndex);
3076 fp.setEndIndex(stringIndex + 1);
3077 positions.add(fp);
3078 }
3079 }
3080 stringIndex++;
3081 }
3082 if (positions != null) {
3083 return positions.toArray(EmptyFieldPositionArray);
3084 }
3085 return EmptyFieldPositionArray;
3086 }
3087
3088 /**
3089 * Appends an affix pattern to the given StringBuffer, quoting special
3090 * characters as needed. Uses the internal affix pattern, if that exists,
3091 * or the literal affix, if the internal affix pattern is null. The
3092 * appended string will generate the same affix pattern (or literal affix)
3093 * when passed to toPattern().
3094 *
3095 * @param buffer the affix string is appended to this
3096 * @param affixPattern a pattern such as posPrefixPattern; may be null
3097 * @param expAffix a corresponding expanded affix, such as positivePrefix.
3112 appendAffix(buffer, affixPattern.substring(pos), localized);
3113 break;
3114 }
3115 if (i > pos) {
3116 appendAffix(buffer, affixPattern.substring(pos, i), localized);
3117 }
3118 char c = affixPattern.charAt(++i);
3119 ++i;
3120 if (c == QUOTE) {
3121 buffer.append(c);
3122 // Fall through and append another QUOTE below
3123 } else if (c == CURRENCY_SIGN &&
3124 i<affixPattern.length() &&
3125 affixPattern.charAt(i) == CURRENCY_SIGN) {
3126 ++i;
3127 buffer.append(c);
3128 // Fall through and append another CURRENCY_SIGN below
3129 } else if (localized) {
3130 switch (c) {
3131 case PATTERN_PERCENT:
3132 c = symbols.getPercent();
3133 break;
3134 case PATTERN_PER_MILLE:
3135 c = symbols.getPerMill();
3136 break;
3137 case PATTERN_MINUS:
3138 c = symbols.getMinusSign();
3139 break;
3140 }
3141 }
3142 buffer.append(c);
3143 }
3144 }
3145 }
3146
3147 /**
3148 * Append an affix to the given StringBuffer, using quotes if
3149 * there are special characters. Single quotes themselves must be
3150 * escaped in either case.
3151 */
3152 private void appendAffix(StringBuffer buffer, String affix, boolean localized) {
3153 boolean needQuote;
3154 if (localized) {
3155 needQuote = affix.indexOf(symbols.getZeroDigit()) >= 0
3156 || affix.indexOf(symbols.getGroupingSeparator()) >= 0
3157 || affix.indexOf(symbols.getDecimalSeparator()) >= 0
3158 || affix.indexOf(symbols.getPercent()) >= 0
3159 || affix.indexOf(symbols.getPerMill()) >= 0
3160 || affix.indexOf(symbols.getDigit()) >= 0
3161 || affix.indexOf(symbols.getPatternSeparator()) >= 0
3162 || affix.indexOf(symbols.getMinusSign()) >= 0
3163 || affix.indexOf(CURRENCY_SIGN) >= 0;
3164 } else {
3165 needQuote = affix.indexOf(PATTERN_ZERO_DIGIT) >= 0
3166 || affix.indexOf(PATTERN_GROUPING_SEPARATOR) >= 0
3167 || affix.indexOf(PATTERN_DECIMAL_SEPARATOR) >= 0
3168 || affix.indexOf(PATTERN_PERCENT) >= 0
3169 || affix.indexOf(PATTERN_PER_MILLE) >= 0
3170 || affix.indexOf(PATTERN_DIGIT) >= 0
3171 || affix.indexOf(PATTERN_SEPARATOR) >= 0
3172 || affix.indexOf(PATTERN_MINUS) >= 0
3173 || affix.indexOf(CURRENCY_SIGN) >= 0;
3174 }
3175 if (needQuote) buffer.append('\'');
3176 if (affix.indexOf('\'') < 0) buffer.append(affix);
3177 else {
3178 for (int j=0; j<affix.length(); ++j) {
3179 char c = affix.charAt(j);
3180 buffer.append(c);
3181 if (c == '\'') buffer.append(c);
3182 }
3218 PATTERN_DIGIT);
3219 }
3220 }
3221 if (useExponentialNotation)
3222 {
3223 result.append(localized ? symbols.getExponentSeparator() :
3224 PATTERN_EXPONENT);
3225 for (i=0; i<minExponentDigits; ++i)
3226 result.append(localized ? symbols.getZeroDigit() :
3227 PATTERN_ZERO_DIGIT);
3228 }
3229 if (j == 1) {
3230 appendAffix(result, posSuffixPattern, positiveSuffix, localized);
3231 if ((negSuffixPattern == posSuffixPattern && // n == p == null
3232 negativeSuffix.equals(positiveSuffix))
3233 || (negSuffixPattern != null &&
3234 negSuffixPattern.equals(posSuffixPattern))) {
3235 if ((negPrefixPattern != null && posPrefixPattern != null &&
3236 negPrefixPattern.equals("'-" + posPrefixPattern)) ||
3237 (negPrefixPattern == posPrefixPattern && // n == p == null
3238 negativePrefix.equals(symbols.getMinusSign() + positivePrefix)))
3239 break;
3240 }
3241 result.append(localized ? symbols.getPatternSeparator() :
3242 PATTERN_SEPARATOR);
3243 } else appendAffix(result, negSuffixPattern, negativeSuffix, localized);
3244 }
3245 return result.toString();
3246 }
3247
3248 /**
3249 * Apply the given pattern to this Format object. A pattern is a
3250 * short-hand specification for the various formatting properties.
3251 * These properties can also be changed individually through the
3252 * various setter methods.
3253 * <p>
3254 * There is no limit to integer digits set
3255 * by this routine, since that is the typical end-user desire;
3256 * use setMaximumInteger if you want to set a real value.
3257 * For negative numbers, use a second pattern, separated by a semicolon
3258 * <P>Example <code>"#,#00.0#"</code> → 1,234.56
3259 * <P>This means a minimum of 2 integer digits, 1 fraction digit, and
3260 * a maximum of 2 fraction digits.
3261 * <p>Example: <code>"#,#00.0#;(#,#00.0#)"</code> for negatives in
3262 * parentheses.
3263 * <p>In negative patterns, the minimum and maximum counts are ignored;
3264 * these are presumed to be set in the positive pattern.
3265 *
3266 * @param pattern a new pattern
3267 * @exception NullPointerException if <code>pattern</code> is null
3268 * @exception IllegalArgumentException if the given pattern is invalid.
3269 */
3270 public void applyPattern(String pattern) {
3271 applyPattern(pattern, false);
3272 }
3273
3274 /**
3275 * Apply the given pattern to this Format object. The pattern
3276 * is assumed to be in a localized notation. A pattern is a
3277 * short-hand specification for the various formatting properties.
3278 * These properties can also be changed individually through the
3279 * various setter methods.
3280 * <p>
3281 * There is no limit to integer digits set
3282 * by this routine, since that is the typical end-user desire;
3283 * use setMaximumInteger if you want to set a real value.
3284 * For negative numbers, use a second pattern, separated by a semicolon
3285 * <P>Example <code>"#,#00.0#"</code> → 1,234.56
3286 * <P>This means a minimum of 2 integer digits, 1 fraction digit, and
3287 * a maximum of 2 fraction digits.
3288 * <p>Example: <code>"#,#00.0#;(#,#00.0#)"</code> for negatives in
3289 * parentheses.
3290 * <p>In negative patterns, the minimum and maximum counts are ignored;
3291 * these are presumed to be set in the positive pattern.
3292 *
3293 * @param pattern a new pattern
3294 * @exception NullPointerException if <code>pattern</code> is null
3295 * @exception IllegalArgumentException if the given pattern is invalid.
3296 */
3297 public void applyLocalizedPattern(String pattern) {
3298 applyPattern(pattern, true);
3299 }
3300
3301 /**
3302 * Does the real work of applying a pattern.
3303 */
3304 private void applyPattern(String pattern, boolean localized) {
3305 char zeroDigit = PATTERN_ZERO_DIGIT;
3306 char groupingSeparator = PATTERN_GROUPING_SEPARATOR;
3307 char decimalSeparator = PATTERN_DECIMAL_SEPARATOR;
3308 char percent = PATTERN_PERCENT;
3309 char perMill = PATTERN_PER_MILLE;
3310 char digit = PATTERN_DIGIT;
3311 char separator = PATTERN_SEPARATOR;
3312 String exponent = PATTERN_EXPONENT;
3313 char minus = PATTERN_MINUS;
3314 if (localized) {
3618 setMinimumFractionDigits(0);
3619 setMaximumFractionDigits(MAXIMUM_FRACTION_DIGITS);
3620 }
3621
3622 // If there was no negative pattern, or if the negative pattern is
3623 // identical to the positive pattern, then prepend the minus sign to
3624 // the positive pattern to form the negative pattern.
3625 if (!gotNegative ||
3626 (negPrefixPattern.equals(posPrefixPattern)
3627 && negSuffixPattern.equals(posSuffixPattern))) {
3628 negSuffixPattern = posSuffixPattern;
3629 negPrefixPattern = "'-" + posPrefixPattern;
3630 }
3631
3632 expandAffixes();
3633 }
3634
3635 /**
3636 * Sets the maximum number of digits allowed in the integer portion of a
3637 * number.
3638 * For formatting numbers other than <code>BigInteger</code> and
3639 * <code>BigDecimal</code> objects, the lower of <code>newValue</code> and
3640 * 309 is used. Negative input values are replaced with 0.
3641 * @see NumberFormat#setMaximumIntegerDigits
3642 */
3643 @Override
3644 public void setMaximumIntegerDigits(int newValue) {
3645 maximumIntegerDigits = Math.min(Math.max(0, newValue), MAXIMUM_INTEGER_DIGITS);
3646 super.setMaximumIntegerDigits((maximumIntegerDigits > DOUBLE_INTEGER_DIGITS) ?
3647 DOUBLE_INTEGER_DIGITS : maximumIntegerDigits);
3648 if (minimumIntegerDigits > maximumIntegerDigits) {
3649 minimumIntegerDigits = maximumIntegerDigits;
3650 super.setMinimumIntegerDigits((minimumIntegerDigits > DOUBLE_INTEGER_DIGITS) ?
3651 DOUBLE_INTEGER_DIGITS : minimumIntegerDigits);
3652 }
3653 fastPathCheckNeeded = true;
3654 }
3655
3656 /**
3657 * Sets the minimum number of digits allowed in the integer portion of a
3658 * number.
3659 * For formatting numbers other than <code>BigInteger</code> and
3660 * <code>BigDecimal</code> objects, the lower of <code>newValue</code> and
3661 * 309 is used. Negative input values are replaced with 0.
3662 * @see NumberFormat#setMinimumIntegerDigits
3663 */
3664 @Override
3665 public void setMinimumIntegerDigits(int newValue) {
3666 minimumIntegerDigits = Math.min(Math.max(0, newValue), MAXIMUM_INTEGER_DIGITS);
3667 super.setMinimumIntegerDigits((minimumIntegerDigits > DOUBLE_INTEGER_DIGITS) ?
3668 DOUBLE_INTEGER_DIGITS : minimumIntegerDigits);
3669 if (minimumIntegerDigits > maximumIntegerDigits) {
3670 maximumIntegerDigits = minimumIntegerDigits;
3671 super.setMaximumIntegerDigits((maximumIntegerDigits > DOUBLE_INTEGER_DIGITS) ?
3672 DOUBLE_INTEGER_DIGITS : maximumIntegerDigits);
3673 }
3674 fastPathCheckNeeded = true;
3675 }
3676
3677 /**
3678 * Sets the maximum number of digits allowed in the fraction portion of a
3679 * number.
3680 * For formatting numbers other than <code>BigInteger</code> and
3681 * <code>BigDecimal</code> objects, the lower of <code>newValue</code> and
3682 * 340 is used. Negative input values are replaced with 0.
3683 * @see NumberFormat#setMaximumFractionDigits
3684 */
3685 @Override
3686 public void setMaximumFractionDigits(int newValue) {
3687 maximumFractionDigits = Math.min(Math.max(0, newValue), MAXIMUM_FRACTION_DIGITS);
3688 super.setMaximumFractionDigits((maximumFractionDigits > DOUBLE_FRACTION_DIGITS) ?
3689 DOUBLE_FRACTION_DIGITS : maximumFractionDigits);
3690 if (minimumFractionDigits > maximumFractionDigits) {
3691 minimumFractionDigits = maximumFractionDigits;
3692 super.setMinimumFractionDigits((minimumFractionDigits > DOUBLE_FRACTION_DIGITS) ?
3693 DOUBLE_FRACTION_DIGITS : minimumFractionDigits);
3694 }
3695 fastPathCheckNeeded = true;
3696 }
3697
3698 /**
3699 * Sets the minimum number of digits allowed in the fraction portion of a
3700 * number.
3701 * For formatting numbers other than <code>BigInteger</code> and
3702 * <code>BigDecimal</code> objects, the lower of <code>newValue</code> and
3703 * 340 is used. Negative input values are replaced with 0.
3704 * @see NumberFormat#setMinimumFractionDigits
3705 */
3706 @Override
3707 public void setMinimumFractionDigits(int newValue) {
3708 minimumFractionDigits = Math.min(Math.max(0, newValue), MAXIMUM_FRACTION_DIGITS);
3709 super.setMinimumFractionDigits((minimumFractionDigits > DOUBLE_FRACTION_DIGITS) ?
3710 DOUBLE_FRACTION_DIGITS : minimumFractionDigits);
3711 if (minimumFractionDigits > maximumFractionDigits) {
3712 maximumFractionDigits = minimumFractionDigits;
3713 super.setMaximumFractionDigits((maximumFractionDigits > DOUBLE_FRACTION_DIGITS) ?
3714 DOUBLE_FRACTION_DIGITS : maximumFractionDigits);
3715 }
3716 fastPathCheckNeeded = true;
3717 }
3718
3719 /**
3720 * Gets the maximum number of digits allowed in the integer portion of a
3721 * number.
3722 * For formatting numbers other than <code>BigInteger</code> and
3723 * <code>BigDecimal</code> objects, the lower of the return value and
3724 * 309 is used.
3725 * @see #setMaximumIntegerDigits
3726 */
3727 @Override
3728 public int getMaximumIntegerDigits() {
3729 return maximumIntegerDigits;
3730 }
3731
3732 /**
3733 * Gets the minimum number of digits allowed in the integer portion of a
3734 * number.
3735 * For formatting numbers other than <code>BigInteger</code> and
3736 * <code>BigDecimal</code> objects, the lower of the return value and
3737 * 309 is used.
3738 * @see #setMinimumIntegerDigits
3739 */
3740 @Override
3741 public int getMinimumIntegerDigits() {
3742 return minimumIntegerDigits;
3743 }
3744
3745 /**
3746 * Gets the maximum number of digits allowed in the fraction portion of a
3747 * number.
3748 * For formatting numbers other than <code>BigInteger</code> and
3749 * <code>BigDecimal</code> objects, the lower of the return value and
3750 * 340 is used.
3751 * @see #setMaximumFractionDigits
3752 */
3753 @Override
3754 public int getMaximumFractionDigits() {
3755 return maximumFractionDigits;
3756 }
3757
3758 /**
3759 * Gets the minimum number of digits allowed in the fraction portion of a
3760 * number.
3761 * For formatting numbers other than <code>BigInteger</code> and
3762 * <code>BigDecimal</code> objects, the lower of the return value and
3763 * 340 is used.
3764 * @see #setMinimumFractionDigits
3765 */
3766 @Override
3767 public int getMinimumFractionDigits() {
3768 return minimumFractionDigits;
3769 }
3770
3771 /**
3772 * Gets the currency used by this decimal format when formatting
3773 * currency values.
3774 * The currency is obtained by calling
3775 * {@link DecimalFormatSymbols#getCurrency DecimalFormatSymbols.getCurrency}
3776 * on this number format's symbols.
3777 *
3778 * @return the currency used by this decimal format, or <code>null</code>
3779 * @since 1.4
3780 */
3781 @Override
3782 public Currency getCurrency() {
3783 return symbols.getCurrency();
3784 }
3785
3786 /**
3787 * Sets the currency used by this number format when formatting
3788 * currency values. This does not update the minimum or maximum
3789 * number of fraction digits used by the number format.
3790 * The currency is set by calling
3791 * {@link DecimalFormatSymbols#setCurrency DecimalFormatSymbols.setCurrency}
3792 * on this number format's symbols.
3793 *
3794 * @param currency the new currency to be used by this decimal format
3795 * @exception NullPointerException if <code>currency</code> is null
3796 * @since 1.4
3797 */
3798 @Override
3799 public void setCurrency(Currency currency) {
3800 if (currency != symbols.getCurrency()) {
3801 symbols.setCurrency(currency);
3802 if (isCurrencyFormat) {
3803 expandAffixes();
3804 }
3805 }
3806 fastPathCheckNeeded = true;
3807 }
3808
3809 /**
3810 * Gets the {@link java.math.RoundingMode} used in this DecimalFormat.
3811 *
3812 * @return The <code>RoundingMode</code> used for this DecimalFormat.
3813 * @see #setRoundingMode(RoundingMode)
3814 * @since 1.6
3815 */
3816 @Override
3817 public RoundingMode getRoundingMode() {
3818 return roundingMode;
3819 }
3820
3821 /**
3822 * Sets the {@link java.math.RoundingMode} used in this DecimalFormat.
3823 *
3824 * @param roundingMode The <code>RoundingMode</code> to be used
3825 * @see #getRoundingMode()
3826 * @exception NullPointerException if <code>roundingMode</code> is null.
3827 * @since 1.6
3828 */
3829 @Override
3830 public void setRoundingMode(RoundingMode roundingMode) {
3831 if (roundingMode == null) {
3832 throw new NullPointerException();
3833 }
3834
3835 this.roundingMode = roundingMode;
3836 digitList.setRoundingMode(roundingMode);
3837 fastPathCheckNeeded = true;
3838 }
3839
3840 /**
3841 * Reads the default serializable fields from the stream and performs
3842 * validations and adjustments for older serialized versions. The
3843 * validations and adjustments are:
3844 * <ol>
3845 * <li>
3846 * Verify that the superclass's digit count fields correctly reflect
3847 * the limits imposed on formatting numbers other than
3848 * <code>BigInteger</code> and <code>BigDecimal</code> objects. These
3849 * limits are stored in the superclass for serialization compatibility
3850 * with older versions, while the limits for <code>BigInteger</code> and
3851 * <code>BigDecimal</code> objects are kept in this class.
3852 * If, in the superclass, the minimum or maximum integer digit count is
3853 * larger than <code>DOUBLE_INTEGER_DIGITS</code> or if the minimum or
3854 * maximum fraction digit count is larger than
3855 * <code>DOUBLE_FRACTION_DIGITS</code>, then the stream data is invalid
3856 * and this method throws an <code>InvalidObjectException</code>.
3857 * <li>
3858 * If <code>serialVersionOnStream</code> is less than 4, initialize
3859 * <code>roundingMode</code> to {@link java.math.RoundingMode#HALF_EVEN
3860 * RoundingMode.HALF_EVEN}. This field is new with version 4.
3861 * <li>
3862 * If <code>serialVersionOnStream</code> is less than 3, then call
3863 * the setters for the minimum and maximum integer and fraction digits with
3864 * the values of the corresponding superclass getters to initialize the
3865 * fields in this class. The fields in this class are new with version 3.
3866 * <li>
3867 * If <code>serialVersionOnStream</code> is less than 1, indicating that
3868 * the stream was written by JDK 1.1, initialize
3869 * <code>useExponentialNotation</code>
3870 * to false, since it was not present in JDK 1.1.
3871 * <li>
3872 * Set <code>serialVersionOnStream</code> to the maximum allowed value so
3873 * that default serialization will work properly if this object is streamed
3874 * out again.
3875 * </ol>
3876 *
3877 * <p>Stream versions older than 2 will not have the affix pattern variables
3878 * <code>posPrefixPattern</code> etc. As a result, they will be initialized
3879 * to <code>null</code>, which means the affix strings will be taken as
3880 * literal values. This is exactly what we want, since that corresponds to
3881 * the pre-version-2 behavior.
3882 */
3883 private void readObject(ObjectInputStream stream)
3884 throws IOException, ClassNotFoundException
3885 {
3886 stream.defaultReadObject();
3887 digitList = new DigitList();
3888
3889 // We force complete fast-path reinitialization when the instance is
3890 // deserialized. See clone() comment on fastPathCheckNeeded.
3891 fastPathCheckNeeded = true;
3892 isFastPath = false;
3893 fastPathData = null;
3894
3895 if (serialVersionOnStream < 4) {
3896 setRoundingMode(RoundingMode.HALF_EVEN);
3897 } else {
3898 setRoundingMode(getRoundingMode());
3899 }
3943
3944 /**
3945 * The symbol used as a prefix when formatting negative numbers, e.g. "-".
3946 *
3947 * @serial
3948 * @see #getNegativePrefix
3949 */
3950 private String negativePrefix = "-";
3951
3952 /**
3953 * The symbol used as a suffix when formatting negative numbers.
3954 * This is often an empty string.
3955 *
3956 * @serial
3957 * @see #getNegativeSuffix
3958 */
3959 private String negativeSuffix = "";
3960
3961 /**
3962 * The prefix pattern for non-negative numbers. This variable corresponds
3963 * to <code>positivePrefix</code>.
3964 *
3965 * <p>This pattern is expanded by the method <code>expandAffix()</code> to
3966 * <code>positivePrefix</code> to update the latter to reflect changes in
3967 * <code>symbols</code>. If this variable is <code>null</code> then
3968 * <code>positivePrefix</code> is taken as a literal value that does not
3969 * change when <code>symbols</code> changes. This variable is always
3970 * <code>null</code> for <code>DecimalFormat</code> objects older than
3971 * stream version 2 restored from stream.
3972 *
3973 * @serial
3974 * @since 1.3
3975 */
3976 private String posPrefixPattern;
3977
3978 /**
3979 * The suffix pattern for non-negative numbers. This variable corresponds
3980 * to <code>positiveSuffix</code>. This variable is analogous to
3981 * <code>posPrefixPattern</code>; see that variable for further
3982 * documentation.
3983 *
3984 * @serial
3985 * @since 1.3
3986 */
3987 private String posSuffixPattern;
3988
3989 /**
3990 * The prefix pattern for negative numbers. This variable corresponds
3991 * to <code>negativePrefix</code>. This variable is analogous to
3992 * <code>posPrefixPattern</code>; see that variable for further
3993 * documentation.
3994 *
3995 * @serial
3996 * @since 1.3
3997 */
3998 private String negPrefixPattern;
3999
4000 /**
4001 * The suffix pattern for negative numbers. This variable corresponds
4002 * to <code>negativeSuffix</code>. This variable is analogous to
4003 * <code>posPrefixPattern</code>; see that variable for further
4004 * documentation.
4005 *
4006 * @serial
4007 * @since 1.3
4008 */
4009 private String negSuffixPattern;
4010
4011 /**
4012 * The multiplier for use in percent, per mille, etc.
4013 *
4014 * @serial
4015 * @see #getMultiplier
4016 */
4017 private int multiplier = 1;
4018
4019 /**
4020 * The number of digits between grouping separators in the integer
4021 * portion of a number. Must be greater than 0 if
4022 * <code>NumberFormat.groupingUsed</code> is true.
4023 *
4024 * @serial
4025 * @see #getGroupingSize
4026 * @see java.text.NumberFormat#isGroupingUsed
4027 */
4028 private byte groupingSize = 3; // invariant, > 0 if useThousands
4029
4030 /**
4031 * If true, forces the decimal separator to always appear in a formatted
4032 * number, even if the fractional part of the number is zero.
4033 *
4034 * @serial
4035 * @see #isDecimalSeparatorAlwaysShown
4036 */
4037 private boolean decimalSeparatorAlwaysShown = false;
4038
4039 /**
4040 * If true, parse returns BigDecimal wherever possible.
4041 *
4042 * @serial
4043 * @see #isParseBigDecimal
4044 * @since 1.5
4045 */
4046 private boolean parseBigDecimal = false;
4047
4048
4049 /**
4050 * True if this object represents a currency format. This determines
4051 * whether the monetary decimal separator is used instead of the normal one.
4052 */
4053 private transient boolean isCurrencyFormat = false;
4054
4055 /**
4056 * The <code>DecimalFormatSymbols</code> object used by this format.
4057 * It contains the symbols used to format numbers, e.g. the grouping separator,
4058 * decimal separator, and so on.
4059 *
4060 * @serial
4061 * @see #setDecimalFormatSymbols
4062 * @see java.text.DecimalFormatSymbols
4063 */
4064 private DecimalFormatSymbols symbols = null; // LIU new DecimalFormatSymbols();
4065
4066 /**
4067 * True to force the use of exponential (i.e. scientific) notation when formatting
4068 * numbers.
4069 *
4070 * @serial
4071 * @since 1.2
4072 */
4073 private boolean useExponentialNotation; // Newly persistent in the Java 2 platform v.1.2
4074
4075 /**
4076 * FieldPositions describing the positive prefix String. This is
4077 * lazily created. Use <code>getPositivePrefixFieldPositions</code>
4078 * when needed.
4079 */
4080 private transient FieldPosition[] positivePrefixFieldPositions;
4081
4082 /**
4083 * FieldPositions describing the positive suffix String. This is
4084 * lazily created. Use <code>getPositiveSuffixFieldPositions</code>
4085 * when needed.
4086 */
4087 private transient FieldPosition[] positiveSuffixFieldPositions;
4088
4089 /**
4090 * FieldPositions describing the negative prefix String. This is
4091 * lazily created. Use <code>getNegativePrefixFieldPositions</code>
4092 * when needed.
4093 */
4094 private transient FieldPosition[] negativePrefixFieldPositions;
4095
4096 /**
4097 * FieldPositions describing the negative suffix String. This is
4098 * lazily created. Use <code>getNegativeSuffixFieldPositions</code>
4099 * when needed.
4100 */
4101 private transient FieldPosition[] negativeSuffixFieldPositions;
4102
4103 /**
4104 * The minimum number of digits used to display the exponent when a number is
4105 * formatted in exponential notation. This field is ignored if
4106 * <code>useExponentialNotation</code> is not true.
4107 *
4108 * @serial
4109 * @since 1.2
4110 */
4111 private byte minExponentDigits; // Newly persistent in the Java 2 platform v.1.2
4112
4113 /**
4114 * The maximum number of digits allowed in the integer portion of a
4115 * <code>BigInteger</code> or <code>BigDecimal</code> number.
4116 * <code>maximumIntegerDigits</code> must be greater than or equal to
4117 * <code>minimumIntegerDigits</code>.
4118 *
4119 * @serial
4120 * @see #getMaximumIntegerDigits
4121 * @since 1.5
4122 */
4123 private int maximumIntegerDigits = super.getMaximumIntegerDigits();
4124
4125 /**
4126 * The minimum number of digits allowed in the integer portion of a
4127 * <code>BigInteger</code> or <code>BigDecimal</code> number.
4128 * <code>minimumIntegerDigits</code> must be less than or equal to
4129 * <code>maximumIntegerDigits</code>.
4130 *
4131 * @serial
4132 * @see #getMinimumIntegerDigits
4133 * @since 1.5
4134 */
4135 private int minimumIntegerDigits = super.getMinimumIntegerDigits();
4136
4137 /**
4138 * The maximum number of digits allowed in the fractional portion of a
4139 * <code>BigInteger</code> or <code>BigDecimal</code> number.
4140 * <code>maximumFractionDigits</code> must be greater than or equal to
4141 * <code>minimumFractionDigits</code>.
4142 *
4143 * @serial
4144 * @see #getMaximumFractionDigits
4145 * @since 1.5
4146 */
4147 private int maximumFractionDigits = super.getMaximumFractionDigits();
4148
4149 /**
4150 * The minimum number of digits allowed in the fractional portion of a
4151 * <code>BigInteger</code> or <code>BigDecimal</code> number.
4152 * <code>minimumFractionDigits</code> must be less than or equal to
4153 * <code>maximumFractionDigits</code>.
4154 *
4155 * @serial
4156 * @see #getMinimumFractionDigits
4157 * @since 1.5
4158 */
4159 private int minimumFractionDigits = super.getMinimumFractionDigits();
4160
4161 /**
4162 * The {@link java.math.RoundingMode} used in this DecimalFormat.
4163 *
4164 * @serial
4165 * @since 1.6
4166 */
4167 private RoundingMode roundingMode = RoundingMode.HALF_EVEN;
4168
4169 // ------ DecimalFormat fields for fast-path for double algorithm ------
4170
4171 /**
4172 * Helper inner utility class for storing the data used in the fast-path
4173 * algorithm. Almost all fields related to fast-path are encapsulated in
4230 /** The format fast-path status of the instance. Logical state. */
4231 private transient boolean isFastPath = false;
4232
4233 /** Flag stating need of check and reinit fast-path status on next format call. */
4234 private transient boolean fastPathCheckNeeded = true;
4235
4236 /** DecimalFormat reference to its FastPathData */
4237 private transient FastPathData fastPathData;
4238
4239
4240 //----------------------------------------------------------------------
4241
4242 static final int currentSerialVersion = 4;
4243
4244 /**
4245 * The internal serial version which says which version was written.
4246 * Possible values are:
4247 * <ul>
4248 * <li><b>0</b> (default): versions before the Java 2 platform v1.2
4249 * <li><b>1</b>: version for 1.2, which includes the two new fields
4250 * <code>useExponentialNotation</code> and
4251 * <code>minExponentDigits</code>.
4252 * <li><b>2</b>: version for 1.3 and later, which adds four new fields:
4253 * <code>posPrefixPattern</code>, <code>posSuffixPattern</code>,
4254 * <code>negPrefixPattern</code>, and <code>negSuffixPattern</code>.
4255 * <li><b>3</b>: version for 1.5 and later, which adds five new fields:
4256 * <code>maximumIntegerDigits</code>,
4257 * <code>minimumIntegerDigits</code>,
4258 * <code>maximumFractionDigits</code>,
4259 * <code>minimumFractionDigits</code>, and
4260 * <code>parseBigDecimal</code>.
4261 * <li><b>4</b>: version for 1.6 and later, which adds one new field:
4262 * <code>roundingMode</code>.
4263 * </ul>
4264 * @since 1.2
4265 * @serial
4266 */
4267 private int serialVersionOnStream = currentSerialVersion;
4268
4269 //----------------------------------------------------------------------
4270 // CONSTANTS
4271 //----------------------------------------------------------------------
4272
4273 // ------ Fast-Path for double Constants ------
4274
4275 /** Maximum valid integer value for applying fast-path algorithm */
4276 private static final double MAX_INT_AS_DOUBLE = (double) Integer.MAX_VALUE;
4277
4278 /**
4279 * The digit arrays used in the fast-path methods for collecting digits.
4280 * Using 3 constants arrays of chars ensures a very fast collection of digits
4281 */
4282 private static class DigitArrays {
|
1 /*
2 * Copyright (c) 1996, 2019, 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
37 */
38
39 package java.text;
40
41 import java.io.IOException;
42 import java.io.InvalidObjectException;
43 import java.io.ObjectInputStream;
44 import java.math.BigDecimal;
45 import java.math.BigInteger;
46 import java.math.RoundingMode;
47 import java.text.spi.NumberFormatProvider;
48 import java.util.ArrayList;
49 import java.util.Currency;
50 import java.util.Locale;
51 import java.util.concurrent.atomic.AtomicInteger;
52 import java.util.concurrent.atomic.AtomicLong;
53 import sun.util.locale.provider.LocaleProviderAdapter;
54 import sun.util.locale.provider.ResourceBundleBasedAdapter;
55
56 /**
57 * {@code DecimalFormat} is a concrete subclass of
58 * {@code NumberFormat} that formats decimal numbers. It has a variety of
59 * features designed to make it possible to parse and format numbers in any
60 * locale, including support for Western, Arabic, and Indic digits. It also
61 * supports different kinds of numbers, including integers (123), fixed-point
62 * numbers (123.4), scientific notation (1.23E4), percentages (12%), and
63 * currency amounts ($123). All of these can be localized.
64 *
65 * <p>To obtain a {@code NumberFormat} for a specific locale, including the
66 * default locale, call one of {@code NumberFormat}'s factory methods, such
67 * as {@code getInstance()}. In general, do not call the
68 * {@code DecimalFormat} constructors directly, since the
69 * {@code NumberFormat} factory methods may return subclasses other than
70 * {@code DecimalFormat}. If you need to customize the format object, do
71 * something like this:
72 *
73 * <blockquote><pre>
74 * NumberFormat f = NumberFormat.getInstance(loc);
75 * if (f instanceof DecimalFormat) {
76 * ((DecimalFormat) f).setDecimalSeparatorAlwaysShown(true);
77 * }
78 * </pre></blockquote>
79 *
80 * <p>A {@code DecimalFormat} comprises a <em>pattern</em> and a set of
81 * <em>symbols</em>. The pattern may be set directly using
82 * {@code applyPattern()}, or indirectly using the API methods. The
83 * symbols are stored in a {@code DecimalFormatSymbols} object. When using
84 * the {@code NumberFormat} factory methods, the pattern and symbols are
85 * read from localized {@code ResourceBundle}s.
86 *
87 * <h3>Patterns</h3>
88 *
89 * {@code DecimalFormat} patterns have the following syntax:
90 * <blockquote><pre>
91 * <i>Pattern:</i>
92 * <i>PositivePattern</i>
93 * <i>PositivePattern</i> ; <i>NegativePattern</i>
94 * <i>PositivePattern:</i>
95 * <i>Prefix<sub>opt</sub></i> <i>Number</i> <i>Suffix<sub>opt</sub></i>
96 * <i>NegativePattern:</i>
97 * <i>Prefix<sub>opt</sub></i> <i>Number</i> <i>Suffix<sub>opt</sub></i>
98 * <i>Prefix:</i>
99 * any Unicode characters except \uFFFE, \uFFFF, and special characters
100 * <i>Suffix:</i>
101 * any Unicode characters except \uFFFE, \uFFFF, and special characters
102 * <i>Number:</i>
103 * <i>Integer</i> <i>Exponent<sub>opt</sub></i>
104 * <i>Integer</i> . <i>Fraction</i> <i>Exponent<sub>opt</sub></i>
105 * <i>Integer:</i>
106 * <i>MinimumInteger</i>
107 * #
108 * # <i>Integer</i>
109 * # , <i>Integer</i>
110 * <i>MinimumInteger:</i>
111 * 0
112 * 0 <i>MinimumInteger</i>
113 * 0 , <i>MinimumInteger</i>
114 * <i>Fraction:</i>
115 * <i>MinimumFraction<sub>opt</sub></i> <i>OptionalFraction<sub>opt</sub></i>
116 * <i>MinimumFraction:</i>
117 * 0 <i>MinimumFraction<sub>opt</sub></i>
118 * <i>OptionalFraction:</i>
119 * # <i>OptionalFraction<sub>opt</sub></i>
120 * <i>Exponent:</i>
121 * E <i>MinimumExponent</i>
122 * <i>MinimumExponent:</i>
123 * 0 <i>MinimumExponent<sub>opt</sub></i>
124 * </pre></blockquote>
125 *
126 * <p>A {@code DecimalFormat} pattern contains a positive and negative
127 * subpattern, for example, {@code "#,##0.00;(#,##0.00)"}. Each
128 * subpattern has a prefix, numeric part, and suffix. The negative subpattern
129 * is optional; if absent, then the positive subpattern prefixed with the
130 * localized minus sign ({@code '-'} in most locales) is used as the
131 * negative subpattern. That is, {@code "0.00"} alone is equivalent to
132 * {@code "0.00;-0.00"}. If there is an explicit negative subpattern, it
133 * serves only to specify the negative prefix and suffix; the number of digits,
134 * minimal digits, and other characteristics are all the same as the positive
135 * pattern. That means that {@code "#,##0.0#;(#)"} produces precisely
136 * the same behavior as {@code "#,##0.0#;(#,##0.0#)"}.
137 *
138 * <p>The prefixes, suffixes, and various symbols used for infinity, digits,
139 * thousands separators, decimal separators, etc. may be set to arbitrary
140 * values, and they will appear properly during formatting. However, care must
141 * be taken that the symbols and strings do not conflict, or parsing will be
142 * unreliable. For example, either the positive and negative prefixes or the
143 * suffixes must be distinct for {@code DecimalFormat.parse()} to be able
144 * to distinguish positive from negative values. (If they are identical, then
145 * {@code DecimalFormat} will behave as if no negative subpattern was
146 * specified.) Another example is that the decimal separator and thousands
147 * separator should be distinct characters, or parsing will be impossible.
148 *
149 * <p>The grouping separator is commonly used for thousands, but in some
150 * countries it separates ten-thousands. The grouping size is a constant number
151 * of digits between the grouping characters, such as 3 for 100,000,000 or 4 for
152 * 1,0000,0000. If you supply a pattern with multiple grouping characters, the
153 * interval between the last one and the end of the integer is the one that is
154 * used. So {@code "#,##,###,####"} == {@code "######,####"} ==
155 * {@code "##,####,####"}.
156 *
157 * <h4><a id="special_pattern_character">Special Pattern Characters</a></h4>
158 *
159 * <p>Many characters in a pattern are taken literally; they are matched during
160 * parsing and output unchanged during formatting. Special characters, on the
161 * other hand, stand for other characters, strings, or classes of characters.
162 * They must be quoted, unless noted otherwise, if they are to appear in the
163 * prefix or suffix as literals.
164 *
165 * <p>The characters listed here are used in non-localized patterns. Localized
166 * patterns use the corresponding characters taken from this formatter's
167 * {@code DecimalFormatSymbols} object instead, and these characters lose
168 * their special status. Two exceptions are the currency sign and quote, which
169 * are not localized.
170 *
171 * <blockquote>
172 * <table class="striped">
173 * <caption style="display:none">Chart showing symbol, location, localized, and meaning.</caption>
174 * <thead>
175 * <tr>
176 * <th scope="col" style="text-align:left">Symbol
177 * <th scope="col" style="text-align:left">Location
178 * <th scope="col" style="text-align:left">Localized?
179 * <th scope="col" style="text-align:left">Meaning
180 * </thead>
181 * <tbody>
182 * <tr style="vertical-align:top">
183 * <th scope="row">{@code 0}
184 * <td>Number
185 * <td>Yes
186 * <td>Digit
187 * <tr style="vertical-align: top">
188 * <th scope="row">{@code #}
189 * <td>Number
190 * <td>Yes
191 * <td>Digit, zero shows as absent
192 * <tr style="vertical-align:top">
193 * <th scope="row">{@code .}
194 * <td>Number
195 * <td>Yes
196 * <td>Decimal separator or monetary decimal separator
197 * <tr style="vertical-align: top">
198 * <th scope="row">{@code -}
199 * <td>Number
200 * <td>Yes
201 * <td>Minus sign
202 * <tr style="vertical-align:top">
203 * <th scope="row">{@code ,}
204 * <td>Number
205 * <td>Yes
206 * <td>Grouping separator
207 * <tr style="vertical-align: top">
208 * <th scope="row">{@code E}
209 * <td>Number
210 * <td>Yes
211 * <td>Separates mantissa and exponent in scientific notation.
212 * <em>Need not be quoted in prefix or suffix.</em>
213 * <tr style="vertical-align:top">
214 * <th scope="row">{@code ;}
215 * <td>Subpattern boundary
216 * <td>Yes
217 * <td>Separates positive and negative subpatterns
218 * <tr style="vertical-align: top">
219 * <th scope="row">{@code %}
220 * <td>Prefix or suffix
221 * <td>Yes
222 * <td>Multiply by 100 and show as percentage
223 * <tr style="vertical-align:top">
224 * <th scope="row">{@code \u2030}
225 * <td>Prefix or suffix
226 * <td>Yes
227 * <td>Multiply by 1000 and show as per mille value
228 * <tr style="vertical-align: top">
229 * <th scope="row">{@code ¤} ({@code \u00A4})
230 * <td>Prefix or suffix
231 * <td>No
232 * <td>Currency sign, replaced by currency symbol. If
233 * doubled, replaced by international currency symbol.
234 * If present in a pattern, the monetary decimal separator
235 * is used instead of the decimal separator.
236 * <tr style="vertical-align:top">
237 * <th scope="row">{@code '}
238 * <td>Prefix or suffix
239 * <td>No
240 * <td>Used to quote special characters in a prefix or suffix,
241 * for example, {@code "'#'#"} formats 123 to
242 * {@code "#123"}. To create a single quote
243 * itself, use two in a row: {@code "# o''clock"}.
244 * </tbody>
245 * </table>
246 * </blockquote>
247 *
248 * <h4>Scientific Notation</h4>
249 *
250 * <p>Numbers in scientific notation are expressed as the product of a mantissa
251 * and a power of ten, for example, 1234 can be expressed as 1.234 x 10^3. The
252 * mantissa is often in the range 1.0 ≤ x {@literal <} 10.0, but it need not
253 * be.
254 * {@code DecimalFormat} can be instructed to format and parse scientific
255 * notation <em>only via a pattern</em>; there is currently no factory method
256 * that creates a scientific notation format. In a pattern, the exponent
257 * character immediately followed by one or more digit characters indicates
258 * scientific notation. Example: {@code "0.###E0"} formats the number
259 * 1234 as {@code "1.234E3"}.
260 *
261 * <ul>
262 * <li>The number of digit characters after the exponent character gives the
263 * minimum exponent digit count. There is no maximum. Negative exponents are
264 * formatted using the localized minus sign, <em>not</em> the prefix and suffix
265 * from the pattern. This allows patterns such as {@code "0.###E0 m/s"}.
266 *
267 * <li>The minimum and maximum number of integer digits are interpreted
268 * together:
269 *
270 * <ul>
271 * <li>If the maximum number of integer digits is greater than their minimum number
272 * and greater than 1, it forces the exponent to be a multiple of the maximum
273 * number of integer digits, and the minimum number of integer digits to be
274 * interpreted as 1. The most common use of this is to generate
275 * <em>engineering notation</em>, in which the exponent is a multiple of three,
276 * e.g., {@code "##0.#####E0"}. Using this pattern, the number 12345
277 * formats to {@code "12.345E3"}, and 123456 formats to
278 * {@code "123.456E3"}.
279 *
280 * <li>Otherwise, the minimum number of integer digits is achieved by adjusting the
281 * exponent. Example: 0.00123 formatted with {@code "00.###E0"} yields
282 * {@code "12.3E-4"}.
283 * </ul>
284 *
285 * <li>The number of significant digits in the mantissa is the sum of the
286 * <em>minimum integer</em> and <em>maximum fraction</em> digits, and is
287 * unaffected by the maximum integer digits. For example, 12345 formatted with
288 * {@code "##0.##E0"} is {@code "12.3E3"}. To show all digits, set
289 * the significant digits count to zero. The number of significant digits
290 * does not affect parsing.
291 *
292 * <li>Exponential patterns may not contain grouping separators.
293 * </ul>
294 *
295 * <h4>Rounding</h4>
296 *
297 * {@code DecimalFormat} provides rounding modes defined in
298 * {@link java.math.RoundingMode} for formatting. By default, it uses
299 * {@link java.math.RoundingMode#HALF_EVEN RoundingMode.HALF_EVEN}.
300 *
301 * <h4>Digits</h4>
302 *
303 * For formatting, {@code DecimalFormat} uses the ten consecutive
304 * characters starting with the localized zero digit defined in the
305 * {@code DecimalFormatSymbols} object as digits. For parsing, these
306 * digits as well as all Unicode decimal digits, as defined by
307 * {@link Character#digit Character.digit}, are recognized.
308 *
309 * <h4>Special Values</h4>
310 *
311 * <p>{@code NaN} is formatted as a string, which typically has a single character
312 * {@code \uFFFD}. This string is determined by the
313 * {@code DecimalFormatSymbols} object. This is the only value for which
314 * the prefixes and suffixes are not used.
315 *
316 * <p>Infinity is formatted as a string, which typically has a single character
317 * {@code \u221E}, with the positive or negative prefixes and suffixes
318 * applied. The infinity string is determined by the
319 * {@code DecimalFormatSymbols} object.
320 *
321 * <p>Negative zero ({@code "-0"}) parses to
322 * <ul>
323 * <li>{@code BigDecimal(0)} if {@code isParseBigDecimal()} is
324 * true,
325 * <li>{@code Long(0)} if {@code isParseBigDecimal()} is false
326 * and {@code isParseIntegerOnly()} is true,
327 * <li>{@code Double(-0.0)} if both {@code isParseBigDecimal()}
328 * and {@code isParseIntegerOnly()} are false.
329 * </ul>
330 *
331 * <h4><a id="synchronization">Synchronization</a></h4>
332 *
333 * <p>
334 * Decimal formats are generally not synchronized.
335 * It is recommended to create separate format instances for each thread.
336 * If multiple threads access a format concurrently, it must be synchronized
337 * externally.
338 *
339 * <h4>Example</h4>
340 *
341 * <blockquote><pre>{@code
342 * <strong>// Print out a number using the localized number, integer, currency,
343 * // and percent format for each locale</strong>
344 * Locale[] locales = NumberFormat.getAvailableLocales();
345 * double myNumber = -1234.56;
346 * NumberFormat form;
347 * for (int j = 0; j < 4; ++j) {
348 * System.out.println("FORMAT");
408 String[] all = adapter.getLocaleResources(def).getNumberPatterns();
409
410 // Always applyPattern after the symbols are set
411 this.symbols = DecimalFormatSymbols.getInstance(def);
412 applyPattern(all[0], false);
413 }
414
415
416 /**
417 * Creates a DecimalFormat using the given pattern and the symbols
418 * for the default {@link java.util.Locale.Category#FORMAT FORMAT} locale.
419 * This is a convenient way to obtain a
420 * DecimalFormat when internationalization is not the main concern.
421 * <p>
422 * To obtain standard formats for a given locale, use the factory methods
423 * on NumberFormat such as getNumberInstance. These factories will
424 * return the most appropriate sub-class of NumberFormat for a given
425 * locale.
426 *
427 * @param pattern a non-localized pattern string.
428 * @exception NullPointerException if {@code pattern} is null
429 * @exception IllegalArgumentException if the given pattern is invalid.
430 * @see java.text.NumberFormat#getInstance
431 * @see java.text.NumberFormat#getNumberInstance
432 * @see java.text.NumberFormat#getCurrencyInstance
433 * @see java.text.NumberFormat#getPercentInstance
434 */
435 public DecimalFormat(String pattern) {
436 // Always applyPattern after the symbols are set
437 this.symbols = DecimalFormatSymbols.getInstance(Locale.getDefault(Locale.Category.FORMAT));
438 applyPattern(pattern, false);
439 }
440
441
442 /**
443 * Creates a DecimalFormat using the given pattern and symbols.
444 * Use this constructor when you need to completely customize the
445 * behavior of the format.
446 * <p>
447 * To obtain standard formats for a given
448 * locale, use the factory methods on NumberFormat such as
458 * @see java.text.NumberFormat#getNumberInstance
459 * @see java.text.NumberFormat#getCurrencyInstance
460 * @see java.text.NumberFormat#getPercentInstance
461 * @see java.text.DecimalFormatSymbols
462 */
463 public DecimalFormat (String pattern, DecimalFormatSymbols symbols) {
464 // Always applyPattern after the symbols are set
465 this.symbols = (DecimalFormatSymbols)symbols.clone();
466 applyPattern(pattern, false);
467 }
468
469
470 // Overrides
471 /**
472 * Formats a number and appends the resulting text to the given string
473 * buffer.
474 * The number can be of any subclass of {@link java.lang.Number}.
475 * <p>
476 * This implementation uses the maximum precision permitted.
477 * @param number the number to format
478 * @param toAppendTo the {@code StringBuffer} to which the formatted
479 * text is to be appended
480 * @param pos keeps track on the position of the field within the
481 * returned string. For example, for formatting a number
482 * {@code 1234567.89} in {@code Locale.US} locale,
483 * if the given {@code fieldPosition} is
484 * {@link NumberFormat#INTEGER_FIELD}, the begin index
485 * and end index of {@code fieldPosition} will be set
486 * to 0 and 9, respectively for the output string
487 * {@code 1,234,567.89}.
488 * @return the value passed in as {@code toAppendTo}
489 * @exception IllegalArgumentException if {@code number} is
490 * null or not an instance of {@code Number}.
491 * @exception NullPointerException if {@code toAppendTo} or
492 * {@code pos} is null
493 * @exception ArithmeticException if rounding is needed with rounding
494 * mode being set to RoundingMode.UNNECESSARY
495 * @see java.text.FieldPosition
496 */
497 @Override
498 public final StringBuffer format(Object number,
499 StringBuffer toAppendTo,
500 FieldPosition pos) {
501 if (number instanceof Long || number instanceof Integer ||
502 number instanceof Short || number instanceof Byte ||
503 number instanceof AtomicInteger ||
504 number instanceof AtomicLong ||
505 (number instanceof BigInteger &&
506 ((BigInteger)number).bitLength () < 64)) {
507 return format(((Number)number).longValue(), toAppendTo, pos);
508 } else if (number instanceof BigDecimal) {
509 return format((BigDecimal)number, toAppendTo, pos);
510 } else if (number instanceof BigInteger) {
511 return format((BigInteger)number, toAppendTo, pos);
512 } else if (number instanceof Number) {
897 } else {
898 maxIntDigits = getMaximumIntegerDigits();
899 minIntDigits = getMinimumIntegerDigits();
900 maxFraDigits = getMaximumFractionDigits();
901 minFraDigits = getMinimumFractionDigits();
902 maximumDigits = maxIntDigits + maxFraDigits;
903 if (maximumDigits < 0) {
904 maximumDigits = Integer.MAX_VALUE;
905 }
906 }
907
908 digitList.set(isNegative, number,
909 useExponentialNotation ? maximumDigits : 0);
910
911 return subformat(result, delegate, isNegative, true,
912 maxIntDigits, minIntDigits, maxFraDigits, minFraDigits);
913 }
914 }
915
916 /**
917 * Formats an Object producing an {@code AttributedCharacterIterator}.
918 * You can use the returned {@code AttributedCharacterIterator}
919 * to build the resulting String, as well as to determine information
920 * about the resulting String.
921 * <p>
922 * Each attribute key of the AttributedCharacterIterator will be of type
923 * {@code NumberFormat.Field}, with the attribute value being the
924 * same as the attribute key.
925 *
926 * @exception NullPointerException if obj is null.
927 * @exception IllegalArgumentException when the Format cannot format the
928 * given object.
929 * @exception ArithmeticException if rounding is needed with rounding
930 * mode being set to RoundingMode.UNNECESSARY
931 * @param obj The object to format
932 * @return AttributedCharacterIterator describing the formatted value.
933 * @since 1.4
934 */
935 @Override
936 public AttributedCharacterIterator formatToCharacterIterator(Object obj) {
937 CharacterIteratorFieldDelegate delegate =
938 new CharacterIteratorFieldDelegate();
939 StringBuffer sb = new StringBuffer();
940
941 if (obj instanceof Double || obj instanceof Float) {
942 format(((Number)obj).doubleValue(), sb, delegate);
943 } else if (obj instanceof Long || obj instanceof Integer ||
1899 // digits, since truncating the exponent would result in an
1900 // unacceptable inaccuracy.
1901 int fieldStart = result.length();
1902
1903 result.append(symbols.getExponentSeparator());
1904
1905 delegate.formatted(Field.EXPONENT_SYMBOL, Field.EXPONENT_SYMBOL,
1906 fieldStart, result.length(), result);
1907
1908 // For zero values, we force the exponent to zero. We
1909 // must do this here, and not earlier, because the value
1910 // is used to determine integer digit count above.
1911 if (digitList.isZero()) {
1912 exponent = 0;
1913 }
1914
1915 boolean negativeExponent = exponent < 0;
1916 if (negativeExponent) {
1917 exponent = -exponent;
1918 fieldStart = result.length();
1919 result.append(symbols.getMinusSignText());
1920 delegate.formatted(Field.EXPONENT_SIGN, Field.EXPONENT_SIGN,
1921 fieldStart, result.length(), result);
1922 }
1923 digitList.set(negativeExponent, exponent);
1924
1925 int eFieldStart = result.length();
1926
1927 for (int i=digitList.decimalAt; i<minExponentDigits; ++i) {
1928 result.append(zero);
1929 }
1930 for (int i=0; i<digitList.decimalAt; ++i) {
1931 result.append((i < digitList.count) ?
1932 (char)(digitList.digits[i] + zeroDelta) : zero);
1933 }
1934 delegate.formatted(Field.EXPONENT, Field.EXPONENT, eFieldStart,
1935 result.length(), result);
1936 } else {
1937 int iFieldStart = result.length();
1938
1939 // Output the integer portion. Here 'count' is the total
2025 result.append(zero);
2026 continue;
2027 }
2028
2029 // Output a digit, if we have any precision left, or a
2030 // zero if we don't. We don't want to output noise digits.
2031 if (!isInteger && digitIndex < digitList.count) {
2032 result.append((char)(digitList.digits[digitIndex++] + zeroDelta));
2033 } else {
2034 result.append(zero);
2035 }
2036 }
2037
2038 // Record field information for caller.
2039 delegate.formatted(FRACTION_FIELD, Field.FRACTION, Field.FRACTION,
2040 fFieldStart, result.length(), result);
2041 }
2042 }
2043
2044 /**
2045 * Appends the String {@code string} to {@code result}.
2046 * {@code delegate} is notified of all the
2047 * {@code FieldPosition}s in {@code positions}.
2048 * <p>
2049 * If one of the {@code FieldPosition}s in {@code positions}
2050 * identifies a {@code SIGN} attribute, it is mapped to
2051 * {@code signAttribute}. This is used
2052 * to map the {@code SIGN} attribute to the {@code EXPONENT}
2053 * attribute as necessary.
2054 * <p>
2055 * This is used by {@code subformat} to add the prefix/suffix.
2056 */
2057 private void append(StringBuffer result, String string,
2058 FieldDelegate delegate,
2059 FieldPosition[] positions,
2060 Format.Field signAttribute) {
2061 int start = result.length();
2062
2063 if (!string.isEmpty()) {
2064 result.append(string);
2065 for (int counter = 0, max = positions.length; counter < max;
2066 counter++) {
2067 FieldPosition fp = positions[counter];
2068 Format.Field attribute = fp.getFieldAttribute();
2069
2070 if (attribute == Field.SIGN) {
2071 attribute = signAttribute;
2072 }
2073 delegate.formatted(attribute, attribute,
2074 start + fp.getBeginIndex(),
2075 start + fp.getEndIndex(), result);
2076 }
2077 }
2078 }
2079
2080 /**
2081 * Parses text from a string to produce a {@code Number}.
2082 * <p>
2083 * The method attempts to parse text starting at the index given by
2084 * {@code pos}.
2085 * If parsing succeeds, then the index of {@code pos} is updated
2086 * to the index after the last character used (parsing does not necessarily
2087 * use all characters up to the end of the string), and the parsed
2088 * number is returned. The updated {@code pos} can be used to
2089 * indicate the starting point for the next call to this method.
2090 * If an error occurs, then the index of {@code pos} is not
2091 * changed, the error index of {@code pos} is set to the index of
2092 * the character where the error occurred, and null is returned.
2093 * <p>
2094 * The subclass returned depends on the value of {@link #isParseBigDecimal}
2095 * as well as on the string being parsed.
2096 * <ul>
2097 * <li>If {@code isParseBigDecimal()} is false (the default),
2098 * most integer values are returned as {@code Long}
2099 * objects, no matter how they are written: {@code "17"} and
2100 * {@code "17.000"} both parse to {@code Long(17)}.
2101 * Values that cannot fit into a {@code Long} are returned as
2102 * {@code Double}s. This includes values with a fractional part,
2103 * infinite values, {@code NaN}, and the value -0.0.
2104 * {@code DecimalFormat} does <em>not</em> decide whether to
2105 * return a {@code Double} or a {@code Long} based on the
2106 * presence of a decimal separator in the source string. Doing so
2107 * would prevent integers that overflow the mantissa of a double,
2108 * such as {@code "-9,223,372,036,854,775,808.00"}, from being
2109 * parsed accurately.
2110 * <p>
2111 * Callers may use the {@code Number} methods
2112 * {@code doubleValue}, {@code longValue}, etc., to obtain
2113 * the type they want.
2114 * <li>If {@code isParseBigDecimal()} is true, values are returned
2115 * as {@code BigDecimal} objects. The values are the ones
2116 * constructed by {@link java.math.BigDecimal#BigDecimal(String)}
2117 * for corresponding strings in locale-independent format. The
2118 * special cases negative and positive infinity and NaN are returned
2119 * as {@code Double} instances holding the values of the
2120 * corresponding {@code Double} constants.
2121 * </ul>
2122 * <p>
2123 * {@code DecimalFormat} parses all Unicode characters that represent
2124 * decimal digits, as defined by {@code Character.digit()}. In
2125 * addition, {@code DecimalFormat} also recognizes as digits the ten
2126 * consecutive characters starting with the localized zero digit defined in
2127 * the {@code DecimalFormatSymbols} object.
2128 *
2129 * @param text the string to be parsed
2130 * @param pos A {@code ParsePosition} object with index and error
2131 * index information as described above.
2132 * @return the parsed value, or {@code null} if the parse fails
2133 * @exception NullPointerException if {@code text} or
2134 * {@code pos} is null.
2135 */
2136 @Override
2137 public Number parse(String text, ParsePosition pos) {
2138 // special case NaN
2139 if (text.regionMatches(pos.index, symbols.getNaN(), 0, symbols.getNaN().length())) {
2140 pos.index = pos.index + symbols.getNaN().length();
2141 return Double.valueOf(Double.NaN);
2142 }
2143
2144 boolean[] status = new boolean[STATUS_LENGTH];
2145 if (!subparse(text, pos, positivePrefix, negativePrefix, digitList, false, status)) {
2146 return null;
2147 }
2148
2149 // special case INFINITY
2150 if (status[STATUS_INFINITE]) {
2151 if (status[STATUS_POSITIVE] == (multiplier >= 0)) {
2152 return Double.valueOf(Double.POSITIVE_INFINITY);
2153 } else {
2154 return Double.valueOf(Double.NEGATIVE_INFINITY);
2458 if (isParseIntegerOnly() || sawDecimal) {
2459 break;
2460 }
2461 digits.decimalAt = digitCount; // Not digits.count!
2462 sawDecimal = true;
2463 } else if (!isExponent && ch == grouping && isGroupingUsed()) {
2464 if (sawDecimal) {
2465 break;
2466 }
2467 // Ignore grouping characters, if we are using them, but
2468 // require that they be followed by a digit. Otherwise
2469 // we backup and reprocess them.
2470 backup = position;
2471 } else if (checkExponent && !isExponent && text.regionMatches(position, exponentString, 0, exponentString.length())
2472 && !sawExponent) {
2473 // Process the exponent by recursively calling this method.
2474 ParsePosition pos = new ParsePosition(position + exponentString.length());
2475 boolean[] stat = new boolean[STATUS_LENGTH];
2476 DigitList exponentDigits = new DigitList();
2477
2478 if (subparse(text, pos, "", symbols.getMinusSignText(), exponentDigits, true, stat) &&
2479 exponentDigits.fitsIntoLong(stat[STATUS_POSITIVE], true)) {
2480 position = pos.index; // Advance past the exponent
2481 exponent = (int)exponentDigits.getLong();
2482 if (!stat[STATUS_POSITIVE]) {
2483 exponent = -exponent;
2484 }
2485 sawExponent = true;
2486 }
2487 break; // Whether we fail or succeed, we exit this loop
2488 } else {
2489 break;
2490 }
2491 }
2492
2493 if (backup != -1) {
2494 position = backup;
2495 }
2496
2497 // If there was no decimal point we have an integer
2498 if (!sawDecimal) {
2556 public String getPositivePrefix () {
2557 return positivePrefix;
2558 }
2559
2560 /**
2561 * Set the positive prefix.
2562 * <P>Examples: +123, $123, sFr123
2563 *
2564 * @param newValue the new positive prefix
2565 */
2566 public void setPositivePrefix (String newValue) {
2567 positivePrefix = newValue;
2568 posPrefixPattern = null;
2569 positivePrefixFieldPositions = null;
2570 fastPathCheckNeeded = true;
2571 }
2572
2573 /**
2574 * Returns the FieldPositions of the fields in the prefix used for
2575 * positive numbers. This is not used if the user has explicitly set
2576 * a positive prefix via {@code setPositivePrefix}. This is
2577 * lazily created.
2578 *
2579 * @return FieldPositions in positive prefix
2580 */
2581 private FieldPosition[] getPositivePrefixFieldPositions() {
2582 if (positivePrefixFieldPositions == null) {
2583 if (posPrefixPattern != null) {
2584 positivePrefixFieldPositions = expandAffix(posPrefixPattern);
2585 } else {
2586 positivePrefixFieldPositions = EmptyFieldPositionArray;
2587 }
2588 }
2589 return positivePrefixFieldPositions;
2590 }
2591
2592 /**
2593 * Get the negative prefix.
2594 * <P>Examples: -123, ($123) (with negative suffix), sFr-123
2595 *
2596 * @return the negative prefix
2597 */
2598 public String getNegativePrefix () {
2599 return negativePrefix;
2600 }
2601
2602 /**
2603 * Set the negative prefix.
2604 * <P>Examples: -123, ($123) (with negative suffix), sFr-123
2605 *
2606 * @param newValue the new negative prefix
2607 */
2608 public void setNegativePrefix (String newValue) {
2609 negativePrefix = newValue;
2610 negPrefixPattern = null;
2611 fastPathCheckNeeded = true;
2612 }
2613
2614 /**
2615 * Returns the FieldPositions of the fields in the prefix used for
2616 * negative numbers. This is not used if the user has explicitly set
2617 * a negative prefix via {@code setNegativePrefix}. This is
2618 * lazily created.
2619 *
2620 * @return FieldPositions in positive prefix
2621 */
2622 private FieldPosition[] getNegativePrefixFieldPositions() {
2623 if (negativePrefixFieldPositions == null) {
2624 if (negPrefixPattern != null) {
2625 negativePrefixFieldPositions = expandAffix(negPrefixPattern);
2626 } else {
2627 negativePrefixFieldPositions = EmptyFieldPositionArray;
2628 }
2629 }
2630 return negativePrefixFieldPositions;
2631 }
2632
2633 /**
2634 * Get the positive suffix.
2635 * <P>Example: 123%
2636 *
2637 * @return the positive suffix
2638 */
2639 public String getPositiveSuffix () {
2640 return positiveSuffix;
2641 }
2642
2643 /**
2644 * Set the positive suffix.
2645 * <P>Example: 123%
2646 *
2647 * @param newValue the new positive suffix
2648 */
2649 public void setPositiveSuffix (String newValue) {
2650 positiveSuffix = newValue;
2651 posSuffixPattern = null;
2652 fastPathCheckNeeded = true;
2653 }
2654
2655 /**
2656 * Returns the FieldPositions of the fields in the suffix used for
2657 * positive numbers. This is not used if the user has explicitly set
2658 * a positive suffix via {@code setPositiveSuffix}. This is
2659 * lazily created.
2660 *
2661 * @return FieldPositions in positive prefix
2662 */
2663 private FieldPosition[] getPositiveSuffixFieldPositions() {
2664 if (positiveSuffixFieldPositions == null) {
2665 if (posSuffixPattern != null) {
2666 positiveSuffixFieldPositions = expandAffix(posSuffixPattern);
2667 } else {
2668 positiveSuffixFieldPositions = EmptyFieldPositionArray;
2669 }
2670 }
2671 return positiveSuffixFieldPositions;
2672 }
2673
2674 /**
2675 * Get the negative suffix.
2676 * <P>Examples: -123%, ($123) (with positive suffixes)
2677 *
2678 * @return the negative suffix
2679 */
2680 public String getNegativeSuffix () {
2681 return negativeSuffix;
2682 }
2683
2684 /**
2685 * Set the negative suffix.
2686 * <P>Examples: 123%
2687 *
2688 * @param newValue the new negative suffix
2689 */
2690 public void setNegativeSuffix (String newValue) {
2691 negativeSuffix = newValue;
2692 negSuffixPattern = null;
2693 fastPathCheckNeeded = true;
2694 }
2695
2696 /**
2697 * Returns the FieldPositions of the fields in the suffix used for
2698 * negative numbers. This is not used if the user has explicitly set
2699 * a negative suffix via {@code setNegativeSuffix}. This is
2700 * lazily created.
2701 *
2702 * @return FieldPositions in positive prefix
2703 */
2704 private FieldPosition[] getNegativeSuffixFieldPositions() {
2705 if (negativeSuffixFieldPositions == null) {
2706 if (negSuffixPattern != null) {
2707 negativeSuffixFieldPositions = expandAffix(negSuffixPattern);
2708 } else {
2709 negativeSuffixFieldPositions = EmptyFieldPositionArray;
2710 }
2711 }
2712 return negativeSuffixFieldPositions;
2713 }
2714
2715 /**
2716 * Gets the multiplier for use in percent, per mille, and similar
2717 * formats.
2718 *
2719 * @return the multiplier
2794 */
2795 public boolean isDecimalSeparatorAlwaysShown() {
2796 return decimalSeparatorAlwaysShown;
2797 }
2798
2799 /**
2800 * Allows you to set the behavior of the decimal separator with integers.
2801 * (The decimal separator will always appear with decimals.)
2802 * <P>Example: Decimal ON: 12345 → 12345.; OFF: 12345 → 12345
2803 *
2804 * @param newValue {@code true} if the decimal separator is always shown;
2805 * {@code false} otherwise
2806 */
2807 public void setDecimalSeparatorAlwaysShown(boolean newValue) {
2808 decimalSeparatorAlwaysShown = newValue;
2809 fastPathCheckNeeded = true;
2810 }
2811
2812 /**
2813 * Returns whether the {@link #parse(java.lang.String, java.text.ParsePosition)}
2814 * method returns {@code BigDecimal}. The default value is false.
2815 *
2816 * @return {@code true} if the parse method returns BigDecimal;
2817 * {@code false} otherwise
2818 * @see #setParseBigDecimal
2819 * @since 1.5
2820 */
2821 public boolean isParseBigDecimal() {
2822 return parseBigDecimal;
2823 }
2824
2825 /**
2826 * Sets whether the {@link #parse(java.lang.String, java.text.ParsePosition)}
2827 * method returns {@code BigDecimal}.
2828 *
2829 * @param newValue {@code true} if the parse method returns BigDecimal;
2830 * {@code false} otherwise
2831 * @see #isParseBigDecimal
2832 * @since 1.5
2833 */
2834 public void setParseBigDecimal(boolean newValue) {
2835 parseBigDecimal = newValue;
2836 }
2837
2838 /**
2839 * Standard override; no change in semantics.
2840 */
2841 @Override
2842 public Object clone() {
2843 DecimalFormat other = (DecimalFormat) super.clone();
2844 other.symbols = (DecimalFormatSymbols) symbols.clone();
2845 other.digitList = (DigitList) digitList.clone();
2846
2847 // Fast-path is almost stateless algorithm. The only logical state is the
2974 * @param buffer a scratch StringBuffer; its contents will be lost
2975 * @return the expanded equivalent of pattern
2976 */
2977 private String expandAffix(String pattern, StringBuffer buffer) {
2978 buffer.setLength(0);
2979 for (int i=0; i<pattern.length(); ) {
2980 char c = pattern.charAt(i++);
2981 if (c == QUOTE) {
2982 c = pattern.charAt(i++);
2983 switch (c) {
2984 case CURRENCY_SIGN:
2985 if (i<pattern.length() &&
2986 pattern.charAt(i) == CURRENCY_SIGN) {
2987 ++i;
2988 buffer.append(symbols.getInternationalCurrencySymbol());
2989 } else {
2990 buffer.append(symbols.getCurrencySymbol());
2991 }
2992 continue;
2993 case PATTERN_PERCENT:
2994 buffer.append(symbols.getPercentText());
2995 continue;
2996 case PATTERN_PER_MILLE:
2997 buffer.append(symbols.getPerMillText());
2998 continue;
2999 case PATTERN_MINUS:
3000 buffer.append(symbols.getMinusSignText());
3001 continue;
3002 }
3003 }
3004 buffer.append(c);
3005 }
3006 return buffer.toString();
3007 }
3008
3009 /**
3010 * Expand an affix pattern into an array of FieldPositions describing
3011 * how the pattern would be expanded.
3012 * All characters in the
3013 * pattern are literal unless prefixed by QUOTE. The following characters
3014 * after QUOTE are recognized: PATTERN_PERCENT, PATTERN_PER_MILLE,
3015 * PATTERN_MINUS, and CURRENCY_SIGN. If CURRENCY_SIGN is doubled (QUOTE +
3016 * CURRENCY_SIGN + CURRENCY_SIGN), it is interpreted as an ISO 4217
3017 * currency code. Any other character after a QUOTE represents itself.
3018 * QUOTE must be followed by another character; QUOTE may not occur by
3019 * itself at the end of the pattern.
3020 *
3021 * @param pattern the non-null, possibly empty pattern
3022 * @return FieldPosition array of the resulting fields.
3023 */
3024 private FieldPosition[] expandAffix(String pattern) {
3025 ArrayList<FieldPosition> positions = null;
3026 int stringIndex = 0;
3027 for (int i=0; i<pattern.length(); ) {
3028 char c = pattern.charAt(i++);
3029 if (c == QUOTE) {
3030 Format.Field fieldID = null;
3031 String string = null;
3032 c = pattern.charAt(i++);
3033 switch (c) {
3034 case CURRENCY_SIGN:
3035 if (i<pattern.length() &&
3036 pattern.charAt(i) == CURRENCY_SIGN) {
3037 ++i;
3038 string = symbols.getInternationalCurrencySymbol();
3039 } else {
3040 string = symbols.getCurrencySymbol();
3041 }
3042 fieldID = Field.CURRENCY;
3043 break;
3044 case PATTERN_PERCENT:
3045 string = symbols.getPercentText();
3046 fieldID = Field.PERCENT;
3047 break;
3048 case PATTERN_PER_MILLE:
3049 string = symbols.getPerMillText();
3050 fieldID = Field.PERMILLE;
3051 break;
3052 case PATTERN_MINUS:
3053 string = symbols.getMinusSignText();
3054 fieldID = Field.SIGN;
3055 break;
3056 }
3057
3058 if (fieldID != null && !string.isEmpty()) {
3059 if (positions == null) {
3060 positions = new ArrayList<>(2);
3061 }
3062 FieldPosition fp = new FieldPosition(fieldID);
3063 fp.setBeginIndex(stringIndex);
3064 fp.setEndIndex(stringIndex + string.length());
3065 positions.add(fp);
3066 stringIndex += string.length();
3067 continue;
3068 }
3069 }
3070 stringIndex++;
3071 }
3072 if (positions != null) {
3073 return positions.toArray(EmptyFieldPositionArray);
3074 }
3075 return EmptyFieldPositionArray;
3076 }
3077
3078 /**
3079 * Appends an affix pattern to the given StringBuffer, quoting special
3080 * characters as needed. Uses the internal affix pattern, if that exists,
3081 * or the literal affix, if the internal affix pattern is null. The
3082 * appended string will generate the same affix pattern (or literal affix)
3083 * when passed to toPattern().
3084 *
3085 * @param buffer the affix string is appended to this
3086 * @param affixPattern a pattern such as posPrefixPattern; may be null
3087 * @param expAffix a corresponding expanded affix, such as positivePrefix.
3102 appendAffix(buffer, affixPattern.substring(pos), localized);
3103 break;
3104 }
3105 if (i > pos) {
3106 appendAffix(buffer, affixPattern.substring(pos, i), localized);
3107 }
3108 char c = affixPattern.charAt(++i);
3109 ++i;
3110 if (c == QUOTE) {
3111 buffer.append(c);
3112 // Fall through and append another QUOTE below
3113 } else if (c == CURRENCY_SIGN &&
3114 i<affixPattern.length() &&
3115 affixPattern.charAt(i) == CURRENCY_SIGN) {
3116 ++i;
3117 buffer.append(c);
3118 // Fall through and append another CURRENCY_SIGN below
3119 } else if (localized) {
3120 switch (c) {
3121 case PATTERN_PERCENT:
3122 buffer.append(symbols.getPercentText());
3123 continue;
3124 case PATTERN_PER_MILLE:
3125 buffer.append(symbols.getPerMillText());
3126 continue;
3127 case PATTERN_MINUS:
3128 buffer.append(symbols.getMinusSignText());
3129 continue;
3130 }
3131 }
3132 buffer.append(c);
3133 }
3134 }
3135 }
3136
3137 /**
3138 * Append an affix to the given StringBuffer, using quotes if
3139 * there are special characters. Single quotes themselves must be
3140 * escaped in either case.
3141 */
3142 private void appendAffix(StringBuffer buffer, String affix, boolean localized) {
3143 boolean needQuote;
3144 if (localized) {
3145 needQuote = affix.indexOf(symbols.getZeroDigit()) >= 0
3146 || affix.indexOf(symbols.getGroupingSeparator()) >= 0
3147 || affix.indexOf(symbols.getDecimalSeparator()) >= 0
3148 || affix.indexOf(symbols.getPercentText()) >= 0
3149 || affix.indexOf(symbols.getPerMillText()) >= 0
3150 || affix.indexOf(symbols.getDigit()) >= 0
3151 || affix.indexOf(symbols.getPatternSeparator()) >= 0
3152 || affix.indexOf(symbols.getMinusSignText()) >= 0
3153 || affix.indexOf(CURRENCY_SIGN) >= 0;
3154 } else {
3155 needQuote = affix.indexOf(PATTERN_ZERO_DIGIT) >= 0
3156 || affix.indexOf(PATTERN_GROUPING_SEPARATOR) >= 0
3157 || affix.indexOf(PATTERN_DECIMAL_SEPARATOR) >= 0
3158 || affix.indexOf(PATTERN_PERCENT) >= 0
3159 || affix.indexOf(PATTERN_PER_MILLE) >= 0
3160 || affix.indexOf(PATTERN_DIGIT) >= 0
3161 || affix.indexOf(PATTERN_SEPARATOR) >= 0
3162 || affix.indexOf(PATTERN_MINUS) >= 0
3163 || affix.indexOf(CURRENCY_SIGN) >= 0;
3164 }
3165 if (needQuote) buffer.append('\'');
3166 if (affix.indexOf('\'') < 0) buffer.append(affix);
3167 else {
3168 for (int j=0; j<affix.length(); ++j) {
3169 char c = affix.charAt(j);
3170 buffer.append(c);
3171 if (c == '\'') buffer.append(c);
3172 }
3208 PATTERN_DIGIT);
3209 }
3210 }
3211 if (useExponentialNotation)
3212 {
3213 result.append(localized ? symbols.getExponentSeparator() :
3214 PATTERN_EXPONENT);
3215 for (i=0; i<minExponentDigits; ++i)
3216 result.append(localized ? symbols.getZeroDigit() :
3217 PATTERN_ZERO_DIGIT);
3218 }
3219 if (j == 1) {
3220 appendAffix(result, posSuffixPattern, positiveSuffix, localized);
3221 if ((negSuffixPattern == posSuffixPattern && // n == p == null
3222 negativeSuffix.equals(positiveSuffix))
3223 || (negSuffixPattern != null &&
3224 negSuffixPattern.equals(posSuffixPattern))) {
3225 if ((negPrefixPattern != null && posPrefixPattern != null &&
3226 negPrefixPattern.equals("'-" + posPrefixPattern)) ||
3227 (negPrefixPattern == posPrefixPattern && // n == p == null
3228 negativePrefix.equals(symbols.getMinusSignText() + positivePrefix)))
3229 break;
3230 }
3231 result.append(localized ? symbols.getPatternSeparator() :
3232 PATTERN_SEPARATOR);
3233 } else appendAffix(result, negSuffixPattern, negativeSuffix, localized);
3234 }
3235 return result.toString();
3236 }
3237
3238 /**
3239 * Apply the given pattern to this Format object. A pattern is a
3240 * short-hand specification for the various formatting properties.
3241 * These properties can also be changed individually through the
3242 * various setter methods.
3243 * <p>
3244 * There is no limit to integer digits set
3245 * by this routine, since that is the typical end-user desire;
3246 * use setMaximumInteger if you want to set a real value.
3247 * For negative numbers, use a second pattern, separated by a semicolon
3248 * <P>Example {@code "#,#00.0#"} → 1,234.56
3249 * <P>This means a minimum of 2 integer digits, 1 fraction digit, and
3250 * a maximum of 2 fraction digits.
3251 * <p>Example: {@code "#,#00.0#;(#,#00.0#)"} for negatives in
3252 * parentheses.
3253 * <p>In negative patterns, the minimum and maximum counts are ignored;
3254 * these are presumed to be set in the positive pattern.
3255 *
3256 * @param pattern a new pattern
3257 * @exception NullPointerException if {@code pattern} is null
3258 * @exception IllegalArgumentException if the given pattern is invalid.
3259 */
3260 public void applyPattern(String pattern) {
3261 applyPattern(pattern, false);
3262 }
3263
3264 /**
3265 * Apply the given pattern to this Format object. The pattern
3266 * is assumed to be in a localized notation. A pattern is a
3267 * short-hand specification for the various formatting properties.
3268 * These properties can also be changed individually through the
3269 * various setter methods.
3270 * <p>
3271 * There is no limit to integer digits set
3272 * by this routine, since that is the typical end-user desire;
3273 * use setMaximumInteger if you want to set a real value.
3274 * For negative numbers, use a second pattern, separated by a semicolon
3275 * <P>Example {@code "#,#00.0#"} → 1,234.56
3276 * <P>This means a minimum of 2 integer digits, 1 fraction digit, and
3277 * a maximum of 2 fraction digits.
3278 * <p>Example: {@code "#,#00.0#;(#,#00.0#)"} for negatives in
3279 * parentheses.
3280 * <p>In negative patterns, the minimum and maximum counts are ignored;
3281 * these are presumed to be set in the positive pattern.
3282 *
3283 * @param pattern a new pattern
3284 * @exception NullPointerException if {@code pattern} is null
3285 * @exception IllegalArgumentException if the given pattern is invalid.
3286 */
3287 public void applyLocalizedPattern(String pattern) {
3288 applyPattern(pattern, true);
3289 }
3290
3291 /**
3292 * Does the real work of applying a pattern.
3293 */
3294 private void applyPattern(String pattern, boolean localized) {
3295 char zeroDigit = PATTERN_ZERO_DIGIT;
3296 char groupingSeparator = PATTERN_GROUPING_SEPARATOR;
3297 char decimalSeparator = PATTERN_DECIMAL_SEPARATOR;
3298 char percent = PATTERN_PERCENT;
3299 char perMill = PATTERN_PER_MILLE;
3300 char digit = PATTERN_DIGIT;
3301 char separator = PATTERN_SEPARATOR;
3302 String exponent = PATTERN_EXPONENT;
3303 char minus = PATTERN_MINUS;
3304 if (localized) {
3608 setMinimumFractionDigits(0);
3609 setMaximumFractionDigits(MAXIMUM_FRACTION_DIGITS);
3610 }
3611
3612 // If there was no negative pattern, or if the negative pattern is
3613 // identical to the positive pattern, then prepend the minus sign to
3614 // the positive pattern to form the negative pattern.
3615 if (!gotNegative ||
3616 (negPrefixPattern.equals(posPrefixPattern)
3617 && negSuffixPattern.equals(posSuffixPattern))) {
3618 negSuffixPattern = posSuffixPattern;
3619 negPrefixPattern = "'-" + posPrefixPattern;
3620 }
3621
3622 expandAffixes();
3623 }
3624
3625 /**
3626 * Sets the maximum number of digits allowed in the integer portion of a
3627 * number.
3628 * For formatting numbers other than {@code BigInteger} and
3629 * {@code BigDecimal} objects, the lower of {@code newValue} and
3630 * 309 is used. Negative input values are replaced with 0.
3631 * @see NumberFormat#setMaximumIntegerDigits
3632 */
3633 @Override
3634 public void setMaximumIntegerDigits(int newValue) {
3635 maximumIntegerDigits = Math.min(Math.max(0, newValue), MAXIMUM_INTEGER_DIGITS);
3636 super.setMaximumIntegerDigits((maximumIntegerDigits > DOUBLE_INTEGER_DIGITS) ?
3637 DOUBLE_INTEGER_DIGITS : maximumIntegerDigits);
3638 if (minimumIntegerDigits > maximumIntegerDigits) {
3639 minimumIntegerDigits = maximumIntegerDigits;
3640 super.setMinimumIntegerDigits((minimumIntegerDigits > DOUBLE_INTEGER_DIGITS) ?
3641 DOUBLE_INTEGER_DIGITS : minimumIntegerDigits);
3642 }
3643 fastPathCheckNeeded = true;
3644 }
3645
3646 /**
3647 * Sets the minimum number of digits allowed in the integer portion of a
3648 * number.
3649 * For formatting numbers other than {@code BigInteger} and
3650 * {@code BigDecimal} objects, the lower of {@code newValue} and
3651 * 309 is used. Negative input values are replaced with 0.
3652 * @see NumberFormat#setMinimumIntegerDigits
3653 */
3654 @Override
3655 public void setMinimumIntegerDigits(int newValue) {
3656 minimumIntegerDigits = Math.min(Math.max(0, newValue), MAXIMUM_INTEGER_DIGITS);
3657 super.setMinimumIntegerDigits((minimumIntegerDigits > DOUBLE_INTEGER_DIGITS) ?
3658 DOUBLE_INTEGER_DIGITS : minimumIntegerDigits);
3659 if (minimumIntegerDigits > maximumIntegerDigits) {
3660 maximumIntegerDigits = minimumIntegerDigits;
3661 super.setMaximumIntegerDigits((maximumIntegerDigits > DOUBLE_INTEGER_DIGITS) ?
3662 DOUBLE_INTEGER_DIGITS : maximumIntegerDigits);
3663 }
3664 fastPathCheckNeeded = true;
3665 }
3666
3667 /**
3668 * Sets the maximum number of digits allowed in the fraction portion of a
3669 * number.
3670 * For formatting numbers other than {@code BigInteger} and
3671 * {@code BigDecimal} objects, the lower of {@code newValue} and
3672 * 340 is used. Negative input values are replaced with 0.
3673 * @see NumberFormat#setMaximumFractionDigits
3674 */
3675 @Override
3676 public void setMaximumFractionDigits(int newValue) {
3677 maximumFractionDigits = Math.min(Math.max(0, newValue), MAXIMUM_FRACTION_DIGITS);
3678 super.setMaximumFractionDigits((maximumFractionDigits > DOUBLE_FRACTION_DIGITS) ?
3679 DOUBLE_FRACTION_DIGITS : maximumFractionDigits);
3680 if (minimumFractionDigits > maximumFractionDigits) {
3681 minimumFractionDigits = maximumFractionDigits;
3682 super.setMinimumFractionDigits((minimumFractionDigits > DOUBLE_FRACTION_DIGITS) ?
3683 DOUBLE_FRACTION_DIGITS : minimumFractionDigits);
3684 }
3685 fastPathCheckNeeded = true;
3686 }
3687
3688 /**
3689 * Sets the minimum number of digits allowed in the fraction portion of a
3690 * number.
3691 * For formatting numbers other than {@code BigInteger} and
3692 * {@code BigDecimal} objects, the lower of {@code newValue} and
3693 * 340 is used. Negative input values are replaced with 0.
3694 * @see NumberFormat#setMinimumFractionDigits
3695 */
3696 @Override
3697 public void setMinimumFractionDigits(int newValue) {
3698 minimumFractionDigits = Math.min(Math.max(0, newValue), MAXIMUM_FRACTION_DIGITS);
3699 super.setMinimumFractionDigits((minimumFractionDigits > DOUBLE_FRACTION_DIGITS) ?
3700 DOUBLE_FRACTION_DIGITS : minimumFractionDigits);
3701 if (minimumFractionDigits > maximumFractionDigits) {
3702 maximumFractionDigits = minimumFractionDigits;
3703 super.setMaximumFractionDigits((maximumFractionDigits > DOUBLE_FRACTION_DIGITS) ?
3704 DOUBLE_FRACTION_DIGITS : maximumFractionDigits);
3705 }
3706 fastPathCheckNeeded = true;
3707 }
3708
3709 /**
3710 * Gets the maximum number of digits allowed in the integer portion of a
3711 * number.
3712 * For formatting numbers other than {@code BigInteger} and
3713 * {@code BigDecimal} objects, the lower of the return value and
3714 * 309 is used.
3715 * @see #setMaximumIntegerDigits
3716 */
3717 @Override
3718 public int getMaximumIntegerDigits() {
3719 return maximumIntegerDigits;
3720 }
3721
3722 /**
3723 * Gets the minimum number of digits allowed in the integer portion of a
3724 * number.
3725 * For formatting numbers other than {@code BigInteger} and
3726 * {@code BigDecimal} objects, the lower of the return value and
3727 * 309 is used.
3728 * @see #setMinimumIntegerDigits
3729 */
3730 @Override
3731 public int getMinimumIntegerDigits() {
3732 return minimumIntegerDigits;
3733 }
3734
3735 /**
3736 * Gets the maximum number of digits allowed in the fraction portion of a
3737 * number.
3738 * For formatting numbers other than {@code BigInteger} and
3739 * {@code BigDecimal} objects, the lower of the return value and
3740 * 340 is used.
3741 * @see #setMaximumFractionDigits
3742 */
3743 @Override
3744 public int getMaximumFractionDigits() {
3745 return maximumFractionDigits;
3746 }
3747
3748 /**
3749 * Gets the minimum number of digits allowed in the fraction portion of a
3750 * number.
3751 * For formatting numbers other than {@code BigInteger} and
3752 * {@code BigDecimal} objects, the lower of the return value and
3753 * 340 is used.
3754 * @see #setMinimumFractionDigits
3755 */
3756 @Override
3757 public int getMinimumFractionDigits() {
3758 return minimumFractionDigits;
3759 }
3760
3761 /**
3762 * Gets the currency used by this decimal format when formatting
3763 * currency values.
3764 * The currency is obtained by calling
3765 * {@link DecimalFormatSymbols#getCurrency DecimalFormatSymbols.getCurrency}
3766 * on this number format's symbols.
3767 *
3768 * @return the currency used by this decimal format, or {@code null}
3769 * @since 1.4
3770 */
3771 @Override
3772 public Currency getCurrency() {
3773 return symbols.getCurrency();
3774 }
3775
3776 /**
3777 * Sets the currency used by this number format when formatting
3778 * currency values. This does not update the minimum or maximum
3779 * number of fraction digits used by the number format.
3780 * The currency is set by calling
3781 * {@link DecimalFormatSymbols#setCurrency DecimalFormatSymbols.setCurrency}
3782 * on this number format's symbols.
3783 *
3784 * @param currency the new currency to be used by this decimal format
3785 * @exception NullPointerException if {@code currency} is null
3786 * @since 1.4
3787 */
3788 @Override
3789 public void setCurrency(Currency currency) {
3790 if (currency != symbols.getCurrency()) {
3791 symbols.setCurrency(currency);
3792 if (isCurrencyFormat) {
3793 expandAffixes();
3794 }
3795 }
3796 fastPathCheckNeeded = true;
3797 }
3798
3799 /**
3800 * Gets the {@link java.math.RoundingMode} used in this DecimalFormat.
3801 *
3802 * @return The {@code RoundingMode} used for this DecimalFormat.
3803 * @see #setRoundingMode(RoundingMode)
3804 * @since 1.6
3805 */
3806 @Override
3807 public RoundingMode getRoundingMode() {
3808 return roundingMode;
3809 }
3810
3811 /**
3812 * Sets the {@link java.math.RoundingMode} used in this DecimalFormat.
3813 *
3814 * @param roundingMode The {@code RoundingMode} to be used
3815 * @see #getRoundingMode()
3816 * @exception NullPointerException if {@code roundingMode} is null.
3817 * @since 1.6
3818 */
3819 @Override
3820 public void setRoundingMode(RoundingMode roundingMode) {
3821 if (roundingMode == null) {
3822 throw new NullPointerException();
3823 }
3824
3825 this.roundingMode = roundingMode;
3826 digitList.setRoundingMode(roundingMode);
3827 fastPathCheckNeeded = true;
3828 }
3829
3830 /**
3831 * Reads the default serializable fields from the stream and performs
3832 * validations and adjustments for older serialized versions. The
3833 * validations and adjustments are:
3834 * <ol>
3835 * <li>
3836 * Verify that the superclass's digit count fields correctly reflect
3837 * the limits imposed on formatting numbers other than
3838 * {@code BigInteger} and {@code BigDecimal} objects. These
3839 * limits are stored in the superclass for serialization compatibility
3840 * with older versions, while the limits for {@code BigInteger} and
3841 * {@code BigDecimal} objects are kept in this class.
3842 * If, in the superclass, the minimum or maximum integer digit count is
3843 * larger than {@code DOUBLE_INTEGER_DIGITS} or if the minimum or
3844 * maximum fraction digit count is larger than
3845 * {@code DOUBLE_FRACTION_DIGITS}, then the stream data is invalid
3846 * and this method throws an {@code InvalidObjectException}.
3847 * <li>
3848 * If {@code serialVersionOnStream} is less than 4, initialize
3849 * {@code roundingMode} to {@link java.math.RoundingMode#HALF_EVEN
3850 * RoundingMode.HALF_EVEN}. This field is new with version 4.
3851 * <li>
3852 * If {@code serialVersionOnStream} is less than 3, then call
3853 * the setters for the minimum and maximum integer and fraction digits with
3854 * the values of the corresponding superclass getters to initialize the
3855 * fields in this class. The fields in this class are new with version 3.
3856 * <li>
3857 * If {@code serialVersionOnStream} is less than 1, indicating that
3858 * the stream was written by JDK 1.1, initialize
3859 * {@code useExponentialNotation}
3860 * to false, since it was not present in JDK 1.1.
3861 * <li>
3862 * Set {@code serialVersionOnStream} to the maximum allowed value so
3863 * that default serialization will work properly if this object is streamed
3864 * out again.
3865 * </ol>
3866 *
3867 * <p>Stream versions older than 2 will not have the affix pattern variables
3868 * {@code posPrefixPattern} etc. As a result, they will be initialized
3869 * to {@code null}, which means the affix strings will be taken as
3870 * literal values. This is exactly what we want, since that corresponds to
3871 * the pre-version-2 behavior.
3872 */
3873 private void readObject(ObjectInputStream stream)
3874 throws IOException, ClassNotFoundException
3875 {
3876 stream.defaultReadObject();
3877 digitList = new DigitList();
3878
3879 // We force complete fast-path reinitialization when the instance is
3880 // deserialized. See clone() comment on fastPathCheckNeeded.
3881 fastPathCheckNeeded = true;
3882 isFastPath = false;
3883 fastPathData = null;
3884
3885 if (serialVersionOnStream < 4) {
3886 setRoundingMode(RoundingMode.HALF_EVEN);
3887 } else {
3888 setRoundingMode(getRoundingMode());
3889 }
3933
3934 /**
3935 * The symbol used as a prefix when formatting negative numbers, e.g. "-".
3936 *
3937 * @serial
3938 * @see #getNegativePrefix
3939 */
3940 private String negativePrefix = "-";
3941
3942 /**
3943 * The symbol used as a suffix when formatting negative numbers.
3944 * This is often an empty string.
3945 *
3946 * @serial
3947 * @see #getNegativeSuffix
3948 */
3949 private String negativeSuffix = "";
3950
3951 /**
3952 * The prefix pattern for non-negative numbers. This variable corresponds
3953 * to {@code positivePrefix}.
3954 *
3955 * <p>This pattern is expanded by the method {@code expandAffix()} to
3956 * {@code positivePrefix} to update the latter to reflect changes in
3957 * {@code symbols}. If this variable is {@code null} then
3958 * {@code positivePrefix} is taken as a literal value that does not
3959 * change when {@code symbols} changes. This variable is always
3960 * {@code null} for {@code DecimalFormat} objects older than
3961 * stream version 2 restored from stream.
3962 *
3963 * @serial
3964 * @since 1.3
3965 */
3966 private String posPrefixPattern;
3967
3968 /**
3969 * The suffix pattern for non-negative numbers. This variable corresponds
3970 * to {@code positiveSuffix}. This variable is analogous to
3971 * {@code posPrefixPattern}; see that variable for further
3972 * documentation.
3973 *
3974 * @serial
3975 * @since 1.3
3976 */
3977 private String posSuffixPattern;
3978
3979 /**
3980 * The prefix pattern for negative numbers. This variable corresponds
3981 * to {@code negativePrefix}. This variable is analogous to
3982 * {@code posPrefixPattern}; see that variable for further
3983 * documentation.
3984 *
3985 * @serial
3986 * @since 1.3
3987 */
3988 private String negPrefixPattern;
3989
3990 /**
3991 * The suffix pattern for negative numbers. This variable corresponds
3992 * to {@code negativeSuffix}. This variable is analogous to
3993 * {@code posPrefixPattern}; see that variable for further
3994 * documentation.
3995 *
3996 * @serial
3997 * @since 1.3
3998 */
3999 private String negSuffixPattern;
4000
4001 /**
4002 * The multiplier for use in percent, per mille, etc.
4003 *
4004 * @serial
4005 * @see #getMultiplier
4006 */
4007 private int multiplier = 1;
4008
4009 /**
4010 * The number of digits between grouping separators in the integer
4011 * portion of a number. Must be greater than 0 if
4012 * {@code NumberFormat.groupingUsed} is true.
4013 *
4014 * @serial
4015 * @see #getGroupingSize
4016 * @see java.text.NumberFormat#isGroupingUsed
4017 */
4018 private byte groupingSize = 3; // invariant, > 0 if useThousands
4019
4020 /**
4021 * If true, forces the decimal separator to always appear in a formatted
4022 * number, even if the fractional part of the number is zero.
4023 *
4024 * @serial
4025 * @see #isDecimalSeparatorAlwaysShown
4026 */
4027 private boolean decimalSeparatorAlwaysShown = false;
4028
4029 /**
4030 * If true, parse returns BigDecimal wherever possible.
4031 *
4032 * @serial
4033 * @see #isParseBigDecimal
4034 * @since 1.5
4035 */
4036 private boolean parseBigDecimal = false;
4037
4038
4039 /**
4040 * True if this object represents a currency format. This determines
4041 * whether the monetary decimal separator is used instead of the normal one.
4042 */
4043 private transient boolean isCurrencyFormat = false;
4044
4045 /**
4046 * The {@code DecimalFormatSymbols} object used by this format.
4047 * It contains the symbols used to format numbers, e.g. the grouping separator,
4048 * decimal separator, and so on.
4049 *
4050 * @serial
4051 * @see #setDecimalFormatSymbols
4052 * @see java.text.DecimalFormatSymbols
4053 */
4054 private DecimalFormatSymbols symbols = null; // LIU new DecimalFormatSymbols();
4055
4056 /**
4057 * True to force the use of exponential (i.e. scientific) notation when formatting
4058 * numbers.
4059 *
4060 * @serial
4061 * @since 1.2
4062 */
4063 private boolean useExponentialNotation; // Newly persistent in the Java 2 platform v.1.2
4064
4065 /**
4066 * FieldPositions describing the positive prefix String. This is
4067 * lazily created. Use {@code getPositivePrefixFieldPositions}
4068 * when needed.
4069 */
4070 private transient FieldPosition[] positivePrefixFieldPositions;
4071
4072 /**
4073 * FieldPositions describing the positive suffix String. This is
4074 * lazily created. Use {@code getPositiveSuffixFieldPositions}
4075 * when needed.
4076 */
4077 private transient FieldPosition[] positiveSuffixFieldPositions;
4078
4079 /**
4080 * FieldPositions describing the negative prefix String. This is
4081 * lazily created. Use {@code getNegativePrefixFieldPositions}
4082 * when needed.
4083 */
4084 private transient FieldPosition[] negativePrefixFieldPositions;
4085
4086 /**
4087 * FieldPositions describing the negative suffix String. This is
4088 * lazily created. Use {@code getNegativeSuffixFieldPositions}
4089 * when needed.
4090 */
4091 private transient FieldPosition[] negativeSuffixFieldPositions;
4092
4093 /**
4094 * The minimum number of digits used to display the exponent when a number is
4095 * formatted in exponential notation. This field is ignored if
4096 * {@code useExponentialNotation} is not true.
4097 *
4098 * @serial
4099 * @since 1.2
4100 */
4101 private byte minExponentDigits; // Newly persistent in the Java 2 platform v.1.2
4102
4103 /**
4104 * The maximum number of digits allowed in the integer portion of a
4105 * {@code BigInteger} or {@code BigDecimal} number.
4106 * {@code maximumIntegerDigits} must be greater than or equal to
4107 * {@code minimumIntegerDigits}.
4108 *
4109 * @serial
4110 * @see #getMaximumIntegerDigits
4111 * @since 1.5
4112 */
4113 private int maximumIntegerDigits = super.getMaximumIntegerDigits();
4114
4115 /**
4116 * The minimum number of digits allowed in the integer portion of a
4117 * {@code BigInteger} or {@code BigDecimal} number.
4118 * {@code minimumIntegerDigits} must be less than or equal to
4119 * {@code maximumIntegerDigits}.
4120 *
4121 * @serial
4122 * @see #getMinimumIntegerDigits
4123 * @since 1.5
4124 */
4125 private int minimumIntegerDigits = super.getMinimumIntegerDigits();
4126
4127 /**
4128 * The maximum number of digits allowed in the fractional portion of a
4129 * {@code BigInteger} or {@code BigDecimal} number.
4130 * {@code maximumFractionDigits} must be greater than or equal to
4131 * {@code minimumFractionDigits}.
4132 *
4133 * @serial
4134 * @see #getMaximumFractionDigits
4135 * @since 1.5
4136 */
4137 private int maximumFractionDigits = super.getMaximumFractionDigits();
4138
4139 /**
4140 * The minimum number of digits allowed in the fractional portion of a
4141 * {@code BigInteger} or {@code BigDecimal} number.
4142 * {@code minimumFractionDigits} must be less than or equal to
4143 * {@code maximumFractionDigits}.
4144 *
4145 * @serial
4146 * @see #getMinimumFractionDigits
4147 * @since 1.5
4148 */
4149 private int minimumFractionDigits = super.getMinimumFractionDigits();
4150
4151 /**
4152 * The {@link java.math.RoundingMode} used in this DecimalFormat.
4153 *
4154 * @serial
4155 * @since 1.6
4156 */
4157 private RoundingMode roundingMode = RoundingMode.HALF_EVEN;
4158
4159 // ------ DecimalFormat fields for fast-path for double algorithm ------
4160
4161 /**
4162 * Helper inner utility class for storing the data used in the fast-path
4163 * algorithm. Almost all fields related to fast-path are encapsulated in
4220 /** The format fast-path status of the instance. Logical state. */
4221 private transient boolean isFastPath = false;
4222
4223 /** Flag stating need of check and reinit fast-path status on next format call. */
4224 private transient boolean fastPathCheckNeeded = true;
4225
4226 /** DecimalFormat reference to its FastPathData */
4227 private transient FastPathData fastPathData;
4228
4229
4230 //----------------------------------------------------------------------
4231
4232 static final int currentSerialVersion = 4;
4233
4234 /**
4235 * The internal serial version which says which version was written.
4236 * Possible values are:
4237 * <ul>
4238 * <li><b>0</b> (default): versions before the Java 2 platform v1.2
4239 * <li><b>1</b>: version for 1.2, which includes the two new fields
4240 * {@code useExponentialNotation} and
4241 * {@code minExponentDigits}.
4242 * <li><b>2</b>: version for 1.3 and later, which adds four new fields:
4243 * {@code posPrefixPattern}, {@code posSuffixPattern},
4244 * {@code negPrefixPattern}, and {@code negSuffixPattern}.
4245 * <li><b>3</b>: version for 1.5 and later, which adds five new fields:
4246 * {@code maximumIntegerDigits},
4247 * {@code minimumIntegerDigits},
4248 * {@code maximumFractionDigits},
4249 * {@code minimumFractionDigits}, and
4250 * {@code parseBigDecimal}.
4251 * <li><b>4</b>: version for 1.6 and later, which adds one new field:
4252 * {@code roundingMode}.
4253 * </ul>
4254 * @since 1.2
4255 * @serial
4256 */
4257 private int serialVersionOnStream = currentSerialVersion;
4258
4259 //----------------------------------------------------------------------
4260 // CONSTANTS
4261 //----------------------------------------------------------------------
4262
4263 // ------ Fast-Path for double Constants ------
4264
4265 /** Maximum valid integer value for applying fast-path algorithm */
4266 private static final double MAX_INT_AS_DOUBLE = (double) Integer.MAX_VALUE;
4267
4268 /**
4269 * The digit arrays used in the fast-path methods for collecting digits.
4270 * Using 3 constants arrays of chars ensures a very fast collection of digits
4271 */
4272 private static class DigitArrays {
|