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 23 * questions. 24 */ 25 26 /* 27 * (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved 28 * (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved 29 * 30 * The original version of this source code and documentation is copyrighted 31 * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These 32 * materials are provided under terms of a License Agreement between Taligent 33 * and Sun. This technology is protected by multiple US and International 34 * patents. This notice and attribution to Taligent may not be removed. 35 * Taligent is a registered trademark of Taligent, Inc. 36 * 37 */ 38 39 package java.text; 40 41 import java.io.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"); 349 * for (int i = 0; i < locales.length; ++i) { 350 * if (locales[i].getCountry().length() == 0) { 351 * continue; // Skip language-only locales 352 * } 353 * System.out.print(locales[i].getDisplayName()); 354 * switch (j) { 355 * case 0: 356 * form = NumberFormat.getInstance(locales[i]); break; 357 * case 1: 358 * form = NumberFormat.getIntegerInstance(locales[i]); break; 359 * case 2: 360 * form = NumberFormat.getCurrencyInstance(locales[i]); break; 361 * default: 362 * form = NumberFormat.getPercentInstance(locales[i]); break; 363 * } 364 * if (form instanceof DecimalFormat) { 365 * System.out.print(": " + ((DecimalFormat) form).toPattern()); 366 * } 367 * System.out.print(" -> " + form.format(myNumber)); 368 * try { 369 * System.out.println(" -> " + form.parse(form.format(myNumber))); 370 * } catch (ParseException e) {} 371 * } 372 * } 373 * }</pre></blockquote> 374 * 375 * @see <a href="http://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html">Java Tutorial</a> 376 * @see NumberFormat 377 * @see DecimalFormatSymbols 378 * @see ParsePosition 379 * @author Mark Davis 380 * @author Alan Liu 381 * @since 1.1 382 */ 383 public class DecimalFormat extends NumberFormat { 384 385 /** 386 * Creates a DecimalFormat using the default pattern and symbols 387 * for the default {@link java.util.Locale.Category#FORMAT FORMAT} locale. 388 * This is a convenient way to obtain a 389 * DecimalFormat when internationalization is not the main concern. 390 * <p> 391 * To obtain standard formats for a given locale, use the factory methods 392 * on NumberFormat such as getNumberInstance. These factories will 393 * return the most appropriate sub-class of NumberFormat for a given 394 * locale. 395 * 396 * @see java.text.NumberFormat#getInstance 397 * @see java.text.NumberFormat#getNumberInstance 398 * @see java.text.NumberFormat#getCurrencyInstance 399 * @see java.text.NumberFormat#getPercentInstance 400 */ 401 public DecimalFormat() { 402 // Get the pattern for the default locale. 403 Locale def = Locale.getDefault(Locale.Category.FORMAT); 404 LocaleProviderAdapter adapter = LocaleProviderAdapter.getAdapter(NumberFormatProvider.class, def); 405 if (!(adapter instanceof ResourceBundleBasedAdapter)) { 406 adapter = LocaleProviderAdapter.getResourceBundleBased(); 407 } 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 449 * getInstance or getCurrencyInstance. If you need only minor adjustments 450 * to a standard format, you can modify the format returned by 451 * a NumberFormat factory method. 452 * 453 * @param pattern a non-localized pattern string 454 * @param symbols the set of symbols to be used 455 * @exception NullPointerException if any of the given arguments is null 456 * @exception IllegalArgumentException if the given pattern is invalid 457 * @see java.text.NumberFormat#getInstance 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) { 513 return format(((Number)number).doubleValue(), toAppendTo, pos); 514 } else { 515 throw new IllegalArgumentException("Cannot format given Object as a Number"); 516 } 517 } 518 519 /** 520 * Formats a double to produce a string. 521 * @param number The double to format 522 * @param result where the text is to be appended 523 * @param fieldPosition keeps track on the position of the field within 524 * the returned string. For example, for formatting 525 * a number {@code 1234567.89} in {@code Locale.US} 526 * locale, if the given {@code fieldPosition} is 527 * {@link NumberFormat#INTEGER_FIELD}, the begin index 528 * and end index of {@code fieldPosition} will be set 529 * to 0 and 9, respectively for the output string 530 * {@code 1,234,567.89}. 531 * @exception NullPointerException if {@code result} or 532 * {@code fieldPosition} is {@code null} 533 * @exception ArithmeticException if rounding is needed with rounding 534 * mode being set to RoundingMode.UNNECESSARY 535 * @return The formatted number string 536 * @see java.text.FieldPosition 537 */ 538 @Override 539 public StringBuffer format(double number, StringBuffer result, 540 FieldPosition fieldPosition) { 541 // If fieldPosition is a DontCareFieldPosition instance we can 542 // try to go to fast-path code. 543 boolean tryFastPath = false; 544 if (fieldPosition == DontCareFieldPosition.INSTANCE) 545 tryFastPath = true; 546 else { 547 fieldPosition.setBeginIndex(0); 548 fieldPosition.setEndIndex(0); 549 } 550 551 if (tryFastPath) { 552 String tempResult = fastFormat(number); 553 if (tempResult != null) { 554 result.append(tempResult); 555 return result; 556 } 557 } 558 559 // if fast-path could not work, we fallback to standard code. 560 return format(number, result, fieldPosition.getFieldDelegate()); 561 } 562 563 /** 564 * Formats a double to produce a string. 565 * @param number The double to format 566 * @param result where the text is to be appended 567 * @param delegate notified of locations of sub fields 568 * @exception ArithmeticException if rounding is needed with rounding 569 * mode being set to RoundingMode.UNNECESSARY 570 * @return The formatted number string 571 */ 572 StringBuffer format(double number, StringBuffer result, 573 FieldDelegate delegate) { 574 575 boolean nanOrInfinity = handleNaN(number, result, delegate); 576 if (nanOrInfinity) { 577 return result; 578 } 579 580 /* Detecting whether a double is negative is easy with the exception of 581 * the value -0.0. This is a double which has a zero mantissa (and 582 * exponent), but a negative sign bit. It is semantically distinct from 583 * a zero with a positive sign bit, and this distinction is important 584 * to certain kinds of computations. However, it's a little tricky to 585 * detect, since (-0.0 == 0.0) and !(-0.0 < 0.0). How then, you may 586 * ask, does it behave distinctly from +0.0? Well, 1/(-0.0) == 587 * -Infinity. Proper detection of -0.0 is needed to deal with the 588 * issues raised by bugs 4106658, 4106667, and 4147706. Liu 7/6/98. 589 */ 590 boolean isNegative = ((number < 0.0) || (number == 0.0 && 1/number < 0.0)) ^ (multiplier < 0); 591 592 if (multiplier != 1) { 593 number *= multiplier; 594 } 595 596 nanOrInfinity = handleInfinity(number, result, delegate, isNegative); 597 if (nanOrInfinity) { 598 return result; 599 } 600 601 if (isNegative) { 602 number = -number; 603 } 604 605 // at this point we are guaranteed a nonnegative finite number. 606 assert (number >= 0 && !Double.isInfinite(number)); 607 return doubleSubformat(number, result, delegate, isNegative); 608 } 609 610 /** 611 * Checks if the given {@code number} is {@code Double.NaN}. if yes; 612 * appends the NaN symbol to the result string. The NaN string is 613 * determined by the DecimalFormatSymbols object. 614 * @param number the double number to format 615 * @param result where the text is to be appended 616 * @param delegate notified of locations of sub fields 617 * @return true, if number is a NaN; false otherwise 618 */ 619 boolean handleNaN(double number, StringBuffer result, 620 FieldDelegate delegate) { 621 if (Double.isNaN(number) 622 || (Double.isInfinite(number) && multiplier == 0)) { 623 int iFieldStart = result.length(); 624 result.append(symbols.getNaN()); 625 delegate.formatted(INTEGER_FIELD, Field.INTEGER, Field.INTEGER, 626 iFieldStart, result.length(), result); 627 return true; 628 } 629 return false; 630 } 631 632 /** 633 * Checks if the given {@code number} is {@code Double.NEGATIVE_INFINITY} 634 * or {@code Double.POSITIVE_INFINITY}. if yes; 635 * appends the infinity string to the result string. The infinity string is 636 * determined by the DecimalFormatSymbols object. 637 * @param number the double number to format 638 * @param result where the text is to be appended 639 * @param delegate notified of locations of sub fields 640 * @param isNegative whether the given {@code number} is negative 641 * @return true, if number is a {@code Double.NEGATIVE_INFINITY} or 642 * {@code Double.POSITIVE_INFINITY}; false otherwise 643 */ 644 boolean handleInfinity(double number, StringBuffer result, 645 FieldDelegate delegate, boolean isNegative) { 646 if (Double.isInfinite(number)) { 647 if (isNegative) { 648 append(result, negativePrefix, delegate, 649 getNegativePrefixFieldPositions(), Field.SIGN); 650 } else { 651 append(result, positivePrefix, delegate, 652 getPositivePrefixFieldPositions(), Field.SIGN); 653 } 654 655 int iFieldStart = result.length(); 656 result.append(symbols.getInfinity()); 657 delegate.formatted(INTEGER_FIELD, Field.INTEGER, Field.INTEGER, 658 iFieldStart, result.length(), result); 659 660 if (isNegative) { 661 append(result, negativeSuffix, delegate, 662 getNegativeSuffixFieldPositions(), Field.SIGN); 663 } else { 664 append(result, positiveSuffix, delegate, 665 getPositiveSuffixFieldPositions(), Field.SIGN); 666 } 667 668 return true; 669 } 670 return false; 671 } 672 673 StringBuffer doubleSubformat(double number, StringBuffer result, 674 FieldDelegate delegate, boolean isNegative) { 675 synchronized (digitList) { 676 int maxIntDigits = super.getMaximumIntegerDigits(); 677 int minIntDigits = super.getMinimumIntegerDigits(); 678 int maxFraDigits = super.getMaximumFractionDigits(); 679 int minFraDigits = super.getMinimumFractionDigits(); 680 681 digitList.set(isNegative, number, useExponentialNotation 682 ? maxIntDigits + maxFraDigits : maxFraDigits, 683 !useExponentialNotation); 684 return subformat(result, delegate, isNegative, false, 685 maxIntDigits, minIntDigits, maxFraDigits, minFraDigits); 686 } 687 } 688 689 /** 690 * Format a long to produce a string. 691 * @param number The long to format 692 * @param result where the text is to be appended 693 * @param fieldPosition keeps track on the position of the field within 694 * the returned string. For example, for formatting 695 * a number {@code 123456789} in {@code Locale.US} 696 * locale, if the given {@code fieldPosition} is 697 * {@link NumberFormat#INTEGER_FIELD}, the begin index 698 * and end index of {@code fieldPosition} will be set 699 * to 0 and 11, respectively for the output string 700 * {@code 123,456,789}. 701 * @exception NullPointerException if {@code result} or 702 * {@code fieldPosition} is {@code null} 703 * @exception ArithmeticException if rounding is needed with rounding 704 * mode being set to RoundingMode.UNNECESSARY 705 * @return The formatted number string 706 * @see java.text.FieldPosition 707 */ 708 @Override 709 public StringBuffer format(long number, StringBuffer result, 710 FieldPosition fieldPosition) { 711 fieldPosition.setBeginIndex(0); 712 fieldPosition.setEndIndex(0); 713 714 return format(number, result, fieldPosition.getFieldDelegate()); 715 } 716 717 /** 718 * Format a long to produce a string. 719 * @param number The long to format 720 * @param result where the text is to be appended 721 * @param delegate notified of locations of sub fields 722 * @return The formatted number string 723 * @exception ArithmeticException if rounding is needed with rounding 724 * mode being set to RoundingMode.UNNECESSARY 725 * @see java.text.FieldPosition 726 */ 727 StringBuffer format(long number, StringBuffer result, 728 FieldDelegate delegate) { 729 boolean isNegative = (number < 0); 730 if (isNegative) { 731 number = -number; 732 } 733 734 // In general, long values always represent real finite numbers, so 735 // we don't have to check for +/- Infinity or NaN. However, there 736 // is one case we have to be careful of: The multiplier can push 737 // a number near MIN_VALUE or MAX_VALUE outside the legal range. We 738 // check for this before multiplying, and if it happens we use 739 // BigInteger instead. 740 boolean useBigInteger = false; 741 if (number < 0) { // This can only happen if number == Long.MIN_VALUE. 742 if (multiplier != 0) { 743 useBigInteger = true; 744 } 745 } else if (multiplier != 1 && multiplier != 0) { 746 long cutoff = Long.MAX_VALUE / multiplier; 747 if (cutoff < 0) { 748 cutoff = -cutoff; 749 } 750 useBigInteger = (number > cutoff); 751 } 752 753 if (useBigInteger) { 754 if (isNegative) { 755 number = -number; 756 } 757 BigInteger bigIntegerValue = BigInteger.valueOf(number); 758 return format(bigIntegerValue, result, delegate, true); 759 } 760 761 number *= multiplier; 762 if (number == 0) { 763 isNegative = false; 764 } else { 765 if (multiplier < 0) { 766 number = -number; 767 isNegative = !isNegative; 768 } 769 } 770 771 synchronized(digitList) { 772 int maxIntDigits = super.getMaximumIntegerDigits(); 773 int minIntDigits = super.getMinimumIntegerDigits(); 774 int maxFraDigits = super.getMaximumFractionDigits(); 775 int minFraDigits = super.getMinimumFractionDigits(); 776 777 digitList.set(isNegative, number, 778 useExponentialNotation ? maxIntDigits + maxFraDigits : 0); 779 780 return subformat(result, delegate, isNegative, true, 781 maxIntDigits, minIntDigits, maxFraDigits, minFraDigits); 782 } 783 } 784 785 /** 786 * Formats a BigDecimal to produce a string. 787 * @param number The BigDecimal to format 788 * @param result where the text is to be appended 789 * @param fieldPosition keeps track on the position of the field within 790 * the returned string. For example, for formatting 791 * a number {@code 1234567.89} in {@code Locale.US} 792 * locale, if the given {@code fieldPosition} is 793 * {@link NumberFormat#INTEGER_FIELD}, the begin index 794 * and end index of {@code fieldPosition} will be set 795 * to 0 and 9, respectively for the output string 796 * {@code 1,234,567.89}. 797 * @return The formatted number string 798 * @exception ArithmeticException if rounding is needed with rounding 799 * mode being set to RoundingMode.UNNECESSARY 800 * @see java.text.FieldPosition 801 */ 802 private StringBuffer format(BigDecimal number, StringBuffer result, 803 FieldPosition fieldPosition) { 804 fieldPosition.setBeginIndex(0); 805 fieldPosition.setEndIndex(0); 806 return format(number, result, fieldPosition.getFieldDelegate()); 807 } 808 809 /** 810 * Formats a BigDecimal to produce a string. 811 * @param number The BigDecimal to format 812 * @param result where the text is to be appended 813 * @param delegate notified of locations of sub fields 814 * @exception ArithmeticException if rounding is needed with rounding 815 * mode being set to RoundingMode.UNNECESSARY 816 * @return The formatted number string 817 */ 818 StringBuffer format(BigDecimal number, StringBuffer result, 819 FieldDelegate delegate) { 820 if (multiplier != 1) { 821 number = number.multiply(getBigDecimalMultiplier()); 822 } 823 boolean isNegative = number.signum() == -1; 824 if (isNegative) { 825 number = number.negate(); 826 } 827 828 synchronized(digitList) { 829 int maxIntDigits = getMaximumIntegerDigits(); 830 int minIntDigits = getMinimumIntegerDigits(); 831 int maxFraDigits = getMaximumFractionDigits(); 832 int minFraDigits = getMinimumFractionDigits(); 833 int maximumDigits = maxIntDigits + maxFraDigits; 834 835 digitList.set(isNegative, number, useExponentialNotation ? 836 ((maximumDigits < 0) ? Integer.MAX_VALUE : maximumDigits) : 837 maxFraDigits, !useExponentialNotation); 838 839 return subformat(result, delegate, isNegative, false, 840 maxIntDigits, minIntDigits, maxFraDigits, minFraDigits); 841 } 842 } 843 844 /** 845 * Format a BigInteger to produce a string. 846 * @param number The BigInteger to format 847 * @param result where the text is to be appended 848 * @param fieldPosition keeps track on the position of the field within 849 * the returned string. For example, for formatting 850 * a number {@code 123456789} in {@code Locale.US} 851 * locale, if the given {@code fieldPosition} is 852 * {@link NumberFormat#INTEGER_FIELD}, the begin index 853 * and end index of {@code fieldPosition} will be set 854 * to 0 and 11, respectively for the output string 855 * {@code 123,456,789}. 856 * @return The formatted number string 857 * @exception ArithmeticException if rounding is needed with rounding 858 * mode being set to RoundingMode.UNNECESSARY 859 * @see java.text.FieldPosition 860 */ 861 private StringBuffer format(BigInteger number, StringBuffer result, 862 FieldPosition fieldPosition) { 863 fieldPosition.setBeginIndex(0); 864 fieldPosition.setEndIndex(0); 865 866 return format(number, result, fieldPosition.getFieldDelegate(), false); 867 } 868 869 /** 870 * Format a BigInteger to produce a string. 871 * @param number The BigInteger to format 872 * @param result where the text is to be appended 873 * @param delegate notified of locations of sub fields 874 * @return The formatted number string 875 * @exception ArithmeticException if rounding is needed with rounding 876 * mode being set to RoundingMode.UNNECESSARY 877 * @see java.text.FieldPosition 878 */ 879 StringBuffer format(BigInteger number, StringBuffer result, 880 FieldDelegate delegate, boolean formatLong) { 881 if (multiplier != 1) { 882 number = number.multiply(getBigIntegerMultiplier()); 883 } 884 boolean isNegative = number.signum() == -1; 885 if (isNegative) { 886 number = number.negate(); 887 } 888 889 synchronized(digitList) { 890 int maxIntDigits, minIntDigits, maxFraDigits, minFraDigits, maximumDigits; 891 if (formatLong) { 892 maxIntDigits = super.getMaximumIntegerDigits(); 893 minIntDigits = super.getMinimumIntegerDigits(); 894 maxFraDigits = super.getMaximumFractionDigits(); 895 minFraDigits = super.getMinimumFractionDigits(); 896 maximumDigits = maxIntDigits + maxFraDigits; 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 || 944 obj instanceof Short || obj instanceof Byte || 945 obj instanceof AtomicInteger || obj instanceof AtomicLong) { 946 format(((Number)obj).longValue(), sb, delegate); 947 } else if (obj instanceof BigDecimal) { 948 format((BigDecimal)obj, sb, delegate); 949 } else if (obj instanceof BigInteger) { 950 format((BigInteger)obj, sb, delegate, false); 951 } else if (obj == null) { 952 throw new NullPointerException( 953 "formatToCharacterIterator must be passed non-null object"); 954 } else { 955 throw new IllegalArgumentException( 956 "Cannot format given Object as a Number"); 957 } 958 return delegate.getIterator(sb.toString()); 959 } 960 961 // ==== Begin fast-path formatting logic for double ========================= 962 963 /* Fast-path formatting will be used for format(double ...) methods iff a 964 * number of conditions are met (see checkAndSetFastPathStatus()): 965 * - Only if instance properties meet the right predefined conditions. 966 * - The abs value of the double to format is <= Integer.MAX_VALUE. 967 * 968 * The basic approach is to split the binary to decimal conversion of a 969 * double value into two phases: 970 * * The conversion of the integer portion of the double. 971 * * The conversion of the fractional portion of the double 972 * (limited to two or three digits). 973 * 974 * The isolation and conversion of the integer portion of the double is 975 * straightforward. The conversion of the fraction is more subtle and relies 976 * on some rounding properties of double to the decimal precisions in 977 * question. Using the terminology of BigDecimal, this fast-path algorithm 978 * is applied when a double value has a magnitude less than Integer.MAX_VALUE 979 * and rounding is to nearest even and the destination format has two or 980 * three digits of *scale* (digits after the decimal point). 981 * 982 * Under a rounding to nearest even policy, the returned result is a digit 983 * string of a number in the (in this case decimal) destination format 984 * closest to the exact numerical value of the (in this case binary) input 985 * value. If two destination format numbers are equally distant, the one 986 * with the last digit even is returned. To compute such a correctly rounded 987 * value, some information about digits beyond the smallest returned digit 988 * position needs to be consulted. 989 * 990 * In general, a guard digit, a round digit, and a sticky *bit* are needed 991 * beyond the returned digit position. If the discarded portion of the input 992 * is sufficiently large, the returned digit string is incremented. In round 993 * to nearest even, this threshold to increment occurs near the half-way 994 * point between digits. The sticky bit records if there are any remaining 995 * trailing digits of the exact input value in the new format; the sticky bit 996 * is consulted only in close to half-way rounding cases. 997 * 998 * Given the computation of the digit and bit values, rounding is then 999 * reduced to a table lookup problem. For decimal, the even/odd cases look 1000 * like this: 1001 * 1002 * Last Round Sticky 1003 * 6 5 0 => 6 // exactly halfway, return even digit. 1004 * 6 5 1 => 7 // a little bit more than halfway, round up. 1005 * 7 5 0 => 8 // exactly halfway, round up to even. 1006 * 7 5 1 => 8 // a little bit more than halfway, round up. 1007 * With analogous entries for other even and odd last-returned digits. 1008 * 1009 * However, decimal negative powers of 5 smaller than 0.5 are *not* exactly 1010 * representable as binary fraction. In particular, 0.005 (the round limit 1011 * for a two-digit scale) and 0.0005 (the round limit for a three-digit 1012 * scale) are not representable. Therefore, for input values near these cases 1013 * the sticky bit is known to be set which reduces the rounding logic to: 1014 * 1015 * Last Round Sticky 1016 * 6 5 1 => 7 // a little bit more than halfway, round up. 1017 * 7 5 1 => 8 // a little bit more than halfway, round up. 1018 * 1019 * In other words, if the round digit is 5, the sticky bit is known to be 1020 * set. If the round digit is something other than 5, the sticky bit is not 1021 * relevant. Therefore, some of the logic about whether or not to increment 1022 * the destination *decimal* value can occur based on tests of *binary* 1023 * computations of the binary input number. 1024 */ 1025 1026 /** 1027 * Check validity of using fast-path for this instance. If fast-path is valid 1028 * for this instance, sets fast-path state as true and initializes fast-path 1029 * utility fields as needed. 1030 * 1031 * This method is supposed to be called rarely, otherwise that will break the 1032 * fast-path performance. That means avoiding frequent changes of the 1033 * properties of the instance, since for most properties, each time a change 1034 * happens, a call to this method is needed at the next format call. 1035 * 1036 * FAST-PATH RULES: 1037 * Similar to the default DecimalFormat instantiation case. 1038 * More precisely: 1039 * - HALF_EVEN rounding mode, 1040 * - isGroupingUsed() is true, 1041 * - groupingSize of 3, 1042 * - multiplier is 1, 1043 * - Decimal separator not mandatory, 1044 * - No use of exponential notation, 1045 * - minimumIntegerDigits is exactly 1 and maximumIntegerDigits at least 10 1046 * - For number of fractional digits, the exact values found in the default case: 1047 * Currency : min = max = 2. 1048 * Decimal : min = 0. max = 3. 1049 * 1050 */ 1051 private boolean checkAndSetFastPathStatus() { 1052 1053 boolean fastPathWasOn = isFastPath; 1054 1055 if ((roundingMode == RoundingMode.HALF_EVEN) && 1056 (isGroupingUsed()) && 1057 (groupingSize == 3) && 1058 (multiplier == 1) && 1059 (!decimalSeparatorAlwaysShown) && 1060 (!useExponentialNotation)) { 1061 1062 // The fast-path algorithm is semi-hardcoded against 1063 // minimumIntegerDigits and maximumIntegerDigits. 1064 isFastPath = ((minimumIntegerDigits == 1) && 1065 (maximumIntegerDigits >= 10)); 1066 1067 // The fast-path algorithm is hardcoded against 1068 // minimumFractionDigits and maximumFractionDigits. 1069 if (isFastPath) { 1070 if (isCurrencyFormat) { 1071 if ((minimumFractionDigits != 2) || 1072 (maximumFractionDigits != 2)) 1073 isFastPath = false; 1074 } else if ((minimumFractionDigits != 0) || 1075 (maximumFractionDigits != 3)) 1076 isFastPath = false; 1077 } 1078 } else 1079 isFastPath = false; 1080 1081 resetFastPathData(fastPathWasOn); 1082 fastPathCheckNeeded = false; 1083 1084 /* 1085 * Returns true after successfully checking the fast path condition and 1086 * setting the fast path data. The return value is used by the 1087 * fastFormat() method to decide whether to call the resetFastPathData 1088 * method to reinitialize fast path data or is it already initialized 1089 * in this method. 1090 */ 1091 return true; 1092 } 1093 1094 private void resetFastPathData(boolean fastPathWasOn) { 1095 // Since some instance properties may have changed while still falling 1096 // in the fast-path case, we need to reinitialize fastPathData anyway. 1097 if (isFastPath) { 1098 // We need to instantiate fastPathData if not already done. 1099 if (fastPathData == null) { 1100 fastPathData = new FastPathData(); 1101 } 1102 1103 // Sets up the locale specific constants used when formatting. 1104 // '0' is our default representation of zero. 1105 fastPathData.zeroDelta = symbols.getZeroDigit() - '0'; 1106 fastPathData.groupingChar = symbols.getGroupingSeparator(); 1107 1108 // Sets up fractional constants related to currency/decimal pattern. 1109 fastPathData.fractionalMaxIntBound = (isCurrencyFormat) 1110 ? 99 : 999; 1111 fastPathData.fractionalScaleFactor = (isCurrencyFormat) 1112 ? 100.0d : 1000.0d; 1113 1114 // Records the need for adding prefix or suffix 1115 fastPathData.positiveAffixesRequired 1116 = !positivePrefix.isEmpty() || !positiveSuffix.isEmpty(); 1117 fastPathData.negativeAffixesRequired 1118 = !negativePrefix.isEmpty() || !negativeSuffix.isEmpty(); 1119 1120 // Creates a cached char container for result, with max possible size. 1121 int maxNbIntegralDigits = 10; 1122 int maxNbGroups = 3; 1123 int containerSize 1124 = Math.max(positivePrefix.length(), negativePrefix.length()) 1125 + maxNbIntegralDigits + maxNbGroups + 1 1126 + maximumFractionDigits 1127 + Math.max(positiveSuffix.length(), negativeSuffix.length()); 1128 1129 fastPathData.fastPathContainer = new char[containerSize]; 1130 1131 // Sets up prefix and suffix char arrays constants. 1132 fastPathData.charsPositiveSuffix = positiveSuffix.toCharArray(); 1133 fastPathData.charsNegativeSuffix = negativeSuffix.toCharArray(); 1134 fastPathData.charsPositivePrefix = positivePrefix.toCharArray(); 1135 fastPathData.charsNegativePrefix = negativePrefix.toCharArray(); 1136 1137 // Sets up fixed index positions for integral and fractional digits. 1138 // Sets up decimal point in cached result container. 1139 int longestPrefixLength 1140 = Math.max(positivePrefix.length(), 1141 negativePrefix.length()); 1142 int decimalPointIndex 1143 = maxNbIntegralDigits + maxNbGroups + longestPrefixLength; 1144 1145 fastPathData.integralLastIndex = decimalPointIndex - 1; 1146 fastPathData.fractionalFirstIndex = decimalPointIndex + 1; 1147 fastPathData.fastPathContainer[decimalPointIndex] 1148 = isCurrencyFormat 1149 ? symbols.getMonetaryDecimalSeparator() 1150 : symbols.getDecimalSeparator(); 1151 1152 } else if (fastPathWasOn) { 1153 // Previous state was fast-path and is no more. 1154 // Resets cached array constants. 1155 fastPathData.fastPathContainer = null; 1156 fastPathData.charsPositiveSuffix = null; 1157 fastPathData.charsNegativeSuffix = null; 1158 fastPathData.charsPositivePrefix = null; 1159 fastPathData.charsNegativePrefix = null; 1160 } 1161 } 1162 1163 /** 1164 * Returns true if rounding-up must be done on {@code scaledFractionalPartAsInt}, 1165 * false otherwise. 1166 * 1167 * This is a utility method that takes correct half-even rounding decision on 1168 * passed fractional value at the scaled decimal point (2 digits for currency 1169 * case and 3 for decimal case), when the approximated fractional part after 1170 * scaled decimal point is exactly 0.5d. This is done by means of exact 1171 * calculations on the {@code fractionalPart} floating-point value. 1172 * 1173 * This method is supposed to be called by private {@code fastDoubleFormat} 1174 * method only. 1175 * 1176 * The algorithms used for the exact calculations are : 1177 * 1178 * The <b><i>FastTwoSum</i></b> algorithm, from T.J.Dekker, described in the 1179 * papers "<i>A Floating-Point Technique for Extending the Available 1180 * Precision</i>" by Dekker, and in "<i>Adaptive Precision Floating-Point 1181 * Arithmetic and Fast Robust Geometric Predicates</i>" from J.Shewchuk. 1182 * 1183 * A modified version of <b><i>Sum2S</i></b> cascaded summation described in 1184 * "<i>Accurate Sum and Dot Product</i>" from Takeshi Ogita and All. As 1185 * Ogita says in this paper this is an equivalent of the Kahan-Babuska's 1186 * summation algorithm because we order the terms by magnitude before summing 1187 * them. For this reason we can use the <i>FastTwoSum</i> algorithm rather 1188 * than the more expensive Knuth's <i>TwoSum</i>. 1189 * 1190 * We do this to avoid a more expensive exact "<i>TwoProduct</i>" algorithm, 1191 * like those described in Shewchuk's paper above. See comments in the code 1192 * below. 1193 * 1194 * @param fractionalPart The fractional value on which we take rounding 1195 * decision. 1196 * @param scaledFractionalPartAsInt The integral part of the scaled 1197 * fractional value. 1198 * 1199 * @return the decision that must be taken regarding half-even rounding. 1200 */ 1201 private boolean exactRoundUp(double fractionalPart, 1202 int scaledFractionalPartAsInt) { 1203 1204 /* exactRoundUp() method is called by fastDoubleFormat() only. 1205 * The precondition expected to be verified by the passed parameters is : 1206 * scaledFractionalPartAsInt == 1207 * (int) (fractionalPart * fastPathData.fractionalScaleFactor). 1208 * This is ensured by fastDoubleFormat() code. 1209 */ 1210 1211 /* We first calculate roundoff error made by fastDoubleFormat() on 1212 * the scaled fractional part. We do this with exact calculation on the 1213 * passed fractionalPart. Rounding decision will then be taken from roundoff. 1214 */ 1215 1216 /* ---- TwoProduct(fractionalPart, scale factor (i.e. 1000.0d or 100.0d)). 1217 * 1218 * The below is an optimized exact "TwoProduct" calculation of passed 1219 * fractional part with scale factor, using Ogita's Sum2S cascaded 1220 * summation adapted as Kahan-Babuska equivalent by using FastTwoSum 1221 * (much faster) rather than Knuth's TwoSum. 1222 * 1223 * We can do this because we order the summation from smallest to 1224 * greatest, so that FastTwoSum can be used without any additional error. 1225 * 1226 * The "TwoProduct" exact calculation needs 17 flops. We replace this by 1227 * a cascaded summation of FastTwoSum calculations, each involving an 1228 * exact multiply by a power of 2. 1229 * 1230 * Doing so saves overall 4 multiplications and 1 addition compared to 1231 * using traditional "TwoProduct". 1232 * 1233 * The scale factor is either 100 (currency case) or 1000 (decimal case). 1234 * - when 1000, we replace it by (1024 - 16 - 8) = 1000. 1235 * - when 100, we replace it by (128 - 32 + 4) = 100. 1236 * Every multiplication by a power of 2 (1024, 128, 32, 16, 8, 4) is exact. 1237 * 1238 */ 1239 double approxMax; // Will always be positive. 1240 double approxMedium; // Will always be negative. 1241 double approxMin; 1242 1243 double fastTwoSumApproximation = 0.0d; 1244 double fastTwoSumRoundOff = 0.0d; 1245 double bVirtual = 0.0d; 1246 1247 if (isCurrencyFormat) { 1248 // Scale is 100 = 128 - 32 + 4. 1249 // Multiply by 2**n is a shift. No roundoff. No error. 1250 approxMax = fractionalPart * 128.00d; 1251 approxMedium = - (fractionalPart * 32.00d); 1252 approxMin = fractionalPart * 4.00d; 1253 } else { 1254 // Scale is 1000 = 1024 - 16 - 8. 1255 // Multiply by 2**n is a shift. No roundoff. No error. 1256 approxMax = fractionalPart * 1024.00d; 1257 approxMedium = - (fractionalPart * 16.00d); 1258 approxMin = - (fractionalPart * 8.00d); 1259 } 1260 1261 // Shewchuk/Dekker's FastTwoSum(approxMedium, approxMin). 1262 assert(-approxMedium >= Math.abs(approxMin)); 1263 fastTwoSumApproximation = approxMedium + approxMin; 1264 bVirtual = fastTwoSumApproximation - approxMedium; 1265 fastTwoSumRoundOff = approxMin - bVirtual; 1266 double approxS1 = fastTwoSumApproximation; 1267 double roundoffS1 = fastTwoSumRoundOff; 1268 1269 // Shewchuk/Dekker's FastTwoSum(approxMax, approxS1); 1270 assert(approxMax >= Math.abs(approxS1)); 1271 fastTwoSumApproximation = approxMax + approxS1; 1272 bVirtual = fastTwoSumApproximation - approxMax; 1273 fastTwoSumRoundOff = approxS1 - bVirtual; 1274 double roundoff1000 = fastTwoSumRoundOff; 1275 double approx1000 = fastTwoSumApproximation; 1276 double roundoffTotal = roundoffS1 + roundoff1000; 1277 1278 // Shewchuk/Dekker's FastTwoSum(approx1000, roundoffTotal); 1279 assert(approx1000 >= Math.abs(roundoffTotal)); 1280 fastTwoSumApproximation = approx1000 + roundoffTotal; 1281 bVirtual = fastTwoSumApproximation - approx1000; 1282 1283 // Now we have got the roundoff for the scaled fractional 1284 double scaledFractionalRoundoff = roundoffTotal - bVirtual; 1285 1286 // ---- TwoProduct(fractionalPart, scale (i.e. 1000.0d or 100.0d)) end. 1287 1288 /* ---- Taking the rounding decision 1289 * 1290 * We take rounding decision based on roundoff and half-even rounding 1291 * rule. 1292 * 1293 * The above TwoProduct gives us the exact roundoff on the approximated 1294 * scaled fractional, and we know that this approximation is exactly 1295 * 0.5d, since that has already been tested by the caller 1296 * (fastDoubleFormat). 1297 * 1298 * Decision comes first from the sign of the calculated exact roundoff. 1299 * - Since being exact roundoff, it cannot be positive with a scaled 1300 * fractional less than 0.5d, as well as negative with a scaled 1301 * fractional greater than 0.5d. That leaves us with following 3 cases. 1302 * - positive, thus scaled fractional == 0.500....0fff ==> round-up. 1303 * - negative, thus scaled fractional == 0.499....9fff ==> don't round-up. 1304 * - is zero, thus scaled fractioanl == 0.5 ==> half-even rounding applies : 1305 * we round-up only if the integral part of the scaled fractional is odd. 1306 * 1307 */ 1308 if (scaledFractionalRoundoff > 0.0) { 1309 return true; 1310 } else if (scaledFractionalRoundoff < 0.0) { 1311 return false; 1312 } else if ((scaledFractionalPartAsInt & 1) != 0) { 1313 return true; 1314 } 1315 1316 return false; 1317 1318 // ---- Taking the rounding decision end 1319 } 1320 1321 /** 1322 * Collects integral digits from passed {@code number}, while setting 1323 * grouping chars as needed. Updates {@code firstUsedIndex} accordingly. 1324 * 1325 * Loops downward starting from {@code backwardIndex} position (inclusive). 1326 * 1327 * @param number The int value from which we collect digits. 1328 * @param digitsBuffer The char array container where digits and grouping chars 1329 * are stored. 1330 * @param backwardIndex the position from which we start storing digits in 1331 * digitsBuffer. 1332 * 1333 */ 1334 private void collectIntegralDigits(int number, 1335 char[] digitsBuffer, 1336 int backwardIndex) { 1337 int index = backwardIndex; 1338 int q; 1339 int r; 1340 while (number > 999) { 1341 // Generates 3 digits per iteration. 1342 q = number / 1000; 1343 r = number - (q << 10) + (q << 4) + (q << 3); // -1024 +16 +8 = 1000. 1344 number = q; 1345 1346 digitsBuffer[index--] = DigitArrays.DigitOnes1000[r]; 1347 digitsBuffer[index--] = DigitArrays.DigitTens1000[r]; 1348 digitsBuffer[index--] = DigitArrays.DigitHundreds1000[r]; 1349 digitsBuffer[index--] = fastPathData.groupingChar; 1350 } 1351 1352 // Collects last 3 or less digits. 1353 digitsBuffer[index] = DigitArrays.DigitOnes1000[number]; 1354 if (number > 9) { 1355 digitsBuffer[--index] = DigitArrays.DigitTens1000[number]; 1356 if (number > 99) 1357 digitsBuffer[--index] = DigitArrays.DigitHundreds1000[number]; 1358 } 1359 1360 fastPathData.firstUsedIndex = index; 1361 } 1362 1363 /** 1364 * Collects the 2 (currency) or 3 (decimal) fractional digits from passed 1365 * {@code number}, starting at {@code startIndex} position 1366 * inclusive. There is no punctuation to set here (no grouping chars). 1367 * Updates {@code fastPathData.lastFreeIndex} accordingly. 1368 * 1369 * 1370 * @param number The int value from which we collect digits. 1371 * @param digitsBuffer The char array container where digits are stored. 1372 * @param startIndex the position from which we start storing digits in 1373 * digitsBuffer. 1374 * 1375 */ 1376 private void collectFractionalDigits(int number, 1377 char[] digitsBuffer, 1378 int startIndex) { 1379 int index = startIndex; 1380 1381 char digitOnes = DigitArrays.DigitOnes1000[number]; 1382 char digitTens = DigitArrays.DigitTens1000[number]; 1383 1384 if (isCurrencyFormat) { 1385 // Currency case. Always collects fractional digits. 1386 digitsBuffer[index++] = digitTens; 1387 digitsBuffer[index++] = digitOnes; 1388 } else if (number != 0) { 1389 // Decimal case. Hundreds will always be collected 1390 digitsBuffer[index++] = DigitArrays.DigitHundreds1000[number]; 1391 1392 // Ending zeros won't be collected. 1393 if (digitOnes != '0') { 1394 digitsBuffer[index++] = digitTens; 1395 digitsBuffer[index++] = digitOnes; 1396 } else if (digitTens != '0') 1397 digitsBuffer[index++] = digitTens; 1398 1399 } else 1400 // This is decimal pattern and fractional part is zero. 1401 // We must remove decimal point from result. 1402 index--; 1403 1404 fastPathData.lastFreeIndex = index; 1405 } 1406 1407 /** 1408 * Internal utility. 1409 * Adds the passed {@code prefix} and {@code suffix} to {@code container}. 1410 * 1411 * @param container Char array container which to prepend/append the 1412 * prefix/suffix. 1413 * @param prefix Char sequence to prepend as a prefix. 1414 * @param suffix Char sequence to append as a suffix. 1415 * 1416 */ 1417 // private void addAffixes(boolean isNegative, char[] container) { 1418 private void addAffixes(char[] container, char[] prefix, char[] suffix) { 1419 1420 // We add affixes only if needed (affix length > 0). 1421 int pl = prefix.length; 1422 int sl = suffix.length; 1423 if (pl != 0) prependPrefix(prefix, pl, container); 1424 if (sl != 0) appendSuffix(suffix, sl, container); 1425 1426 } 1427 1428 /** 1429 * Prepends the passed {@code prefix} chars to given result 1430 * {@code container}. Updates {@code fastPathData.firstUsedIndex} 1431 * accordingly. 1432 * 1433 * @param prefix The prefix characters to prepend to result. 1434 * @param len The number of chars to prepend. 1435 * @param container Char array container which to prepend the prefix 1436 */ 1437 private void prependPrefix(char[] prefix, 1438 int len, 1439 char[] container) { 1440 1441 fastPathData.firstUsedIndex -= len; 1442 int startIndex = fastPathData.firstUsedIndex; 1443 1444 // If prefix to prepend is only 1 char long, just assigns this char. 1445 // If prefix is less or equal 4, we use a dedicated algorithm that 1446 // has shown to run faster than System.arraycopy. 1447 // If more than 4, we use System.arraycopy. 1448 if (len == 1) 1449 container[startIndex] = prefix[0]; 1450 else if (len <= 4) { 1451 int dstLower = startIndex; 1452 int dstUpper = dstLower + len - 1; 1453 int srcUpper = len - 1; 1454 container[dstLower] = prefix[0]; 1455 container[dstUpper] = prefix[srcUpper]; 1456 1457 if (len > 2) 1458 container[++dstLower] = prefix[1]; 1459 if (len == 4) 1460 container[--dstUpper] = prefix[2]; 1461 } else 1462 System.arraycopy(prefix, 0, container, startIndex, len); 1463 } 1464 1465 /** 1466 * Appends the passed {@code suffix} chars to given result 1467 * {@code container}. Updates {@code fastPathData.lastFreeIndex} 1468 * accordingly. 1469 * 1470 * @param suffix The suffix characters to append to result. 1471 * @param len The number of chars to append. 1472 * @param container Char array container which to append the suffix 1473 */ 1474 private void appendSuffix(char[] suffix, 1475 int len, 1476 char[] container) { 1477 1478 int startIndex = fastPathData.lastFreeIndex; 1479 1480 // If suffix to append is only 1 char long, just assigns this char. 1481 // If suffix is less or equal 4, we use a dedicated algorithm that 1482 // has shown to run faster than System.arraycopy. 1483 // If more than 4, we use System.arraycopy. 1484 if (len == 1) 1485 container[startIndex] = suffix[0]; 1486 else if (len <= 4) { 1487 int dstLower = startIndex; 1488 int dstUpper = dstLower + len - 1; 1489 int srcUpper = len - 1; 1490 container[dstLower] = suffix[0]; 1491 container[dstUpper] = suffix[srcUpper]; 1492 1493 if (len > 2) 1494 container[++dstLower] = suffix[1]; 1495 if (len == 4) 1496 container[--dstUpper] = suffix[2]; 1497 } else 1498 System.arraycopy(suffix, 0, container, startIndex, len); 1499 1500 fastPathData.lastFreeIndex += len; 1501 } 1502 1503 /** 1504 * Converts digit chars from {@code digitsBuffer} to current locale. 1505 * 1506 * Must be called before adding affixes since we refer to 1507 * {@code fastPathData.firstUsedIndex} and {@code fastPathData.lastFreeIndex}, 1508 * and do not support affixes (for speed reason). 1509 * 1510 * We loop backward starting from last used index in {@code fastPathData}. 1511 * 1512 * @param digitsBuffer The char array container where the digits are stored. 1513 */ 1514 private void localizeDigits(char[] digitsBuffer) { 1515 1516 // We will localize only the digits, using the groupingSize, 1517 // and taking into account fractional part. 1518 1519 // First take into account fractional part. 1520 int digitsCounter = 1521 fastPathData.lastFreeIndex - fastPathData.fractionalFirstIndex; 1522 1523 // The case when there is no fractional digits. 1524 if (digitsCounter < 0) 1525 digitsCounter = groupingSize; 1526 1527 // Only the digits remains to localize. 1528 for (int cursor = fastPathData.lastFreeIndex - 1; 1529 cursor >= fastPathData.firstUsedIndex; 1530 cursor--) { 1531 if (digitsCounter != 0) { 1532 // This is a digit char, we must localize it. 1533 digitsBuffer[cursor] += fastPathData.zeroDelta; 1534 digitsCounter--; 1535 } else { 1536 // Decimal separator or grouping char. Reinit counter only. 1537 digitsCounter = groupingSize; 1538 } 1539 } 1540 } 1541 1542 /** 1543 * This is the main entry point for the fast-path format algorithm. 1544 * 1545 * At this point we are sure to be in the expected conditions to run it. 1546 * This algorithm builds the formatted result and puts it in the dedicated 1547 * {@code fastPathData.fastPathContainer}. 1548 * 1549 * @param d the double value to be formatted. 1550 * @param negative Flag precising if {@code d} is negative. 1551 */ 1552 private void fastDoubleFormat(double d, 1553 boolean negative) { 1554 1555 char[] container = fastPathData.fastPathContainer; 1556 1557 /* 1558 * The principle of the algorithm is to : 1559 * - Break the passed double into its integral and fractional parts 1560 * converted into integers. 1561 * - Then decide if rounding up must be applied or not by following 1562 * the half-even rounding rule, first using approximated scaled 1563 * fractional part. 1564 * - For the difficult cases (approximated scaled fractional part 1565 * being exactly 0.5d), we refine the rounding decision by calling 1566 * exactRoundUp utility method that both calculates the exact roundoff 1567 * on the approximation and takes correct rounding decision. 1568 * - We round-up the fractional part if needed, possibly propagating the 1569 * rounding to integral part if we meet a "all-nine" case for the 1570 * scaled fractional part. 1571 * - We then collect digits from the resulting integral and fractional 1572 * parts, also setting the required grouping chars on the fly. 1573 * - Then we localize the collected digits if needed, and 1574 * - Finally prepend/append prefix/suffix if any is needed. 1575 */ 1576 1577 // Exact integral part of d. 1578 int integralPartAsInt = (int) d; 1579 1580 // Exact fractional part of d (since we subtract it's integral part). 1581 double exactFractionalPart = d - (double) integralPartAsInt; 1582 1583 // Approximated scaled fractional part of d (due to multiplication). 1584 double scaledFractional = 1585 exactFractionalPart * fastPathData.fractionalScaleFactor; 1586 1587 // Exact integral part of scaled fractional above. 1588 int fractionalPartAsInt = (int) scaledFractional; 1589 1590 // Exact fractional part of scaled fractional above. 1591 scaledFractional = scaledFractional - (double) fractionalPartAsInt; 1592 1593 // Only when scaledFractional is exactly 0.5d do we have to do exact 1594 // calculations and take fine-grained rounding decision, since 1595 // approximated results above may lead to incorrect decision. 1596 // Otherwise comparing against 0.5d (strictly greater or less) is ok. 1597 boolean roundItUp = false; 1598 if (scaledFractional >= 0.5d) { 1599 if (scaledFractional == 0.5d) 1600 // Rounding need fine-grained decision. 1601 roundItUp = exactRoundUp(exactFractionalPart, fractionalPartAsInt); 1602 else 1603 roundItUp = true; 1604 1605 if (roundItUp) { 1606 // Rounds up both fractional part (and also integral if needed). 1607 if (fractionalPartAsInt < fastPathData.fractionalMaxIntBound) { 1608 fractionalPartAsInt++; 1609 } else { 1610 // Propagates rounding to integral part since "all nines" case. 1611 fractionalPartAsInt = 0; 1612 integralPartAsInt++; 1613 } 1614 } 1615 } 1616 1617 // Collecting digits. 1618 collectFractionalDigits(fractionalPartAsInt, container, 1619 fastPathData.fractionalFirstIndex); 1620 collectIntegralDigits(integralPartAsInt, container, 1621 fastPathData.integralLastIndex); 1622 1623 // Localizing digits. 1624 if (fastPathData.zeroDelta != 0) 1625 localizeDigits(container); 1626 1627 // Adding prefix and suffix. 1628 if (negative) { 1629 if (fastPathData.negativeAffixesRequired) 1630 addAffixes(container, 1631 fastPathData.charsNegativePrefix, 1632 fastPathData.charsNegativeSuffix); 1633 } else if (fastPathData.positiveAffixesRequired) 1634 addAffixes(container, 1635 fastPathData.charsPositivePrefix, 1636 fastPathData.charsPositiveSuffix); 1637 } 1638 1639 /** 1640 * A fast-path shortcut of format(double) to be called by NumberFormat, or by 1641 * format(double, ...) public methods. 1642 * 1643 * If instance can be applied fast-path and passed double is not NaN or 1644 * Infinity, is in the integer range, we call {@code fastDoubleFormat} 1645 * after changing {@code d} to its positive value if necessary. 1646 * 1647 * Otherwise returns null by convention since fast-path can't be exercized. 1648 * 1649 * @param d The double value to be formatted 1650 * 1651 * @return the formatted result for {@code d} as a string. 1652 */ 1653 String fastFormat(double d) { 1654 boolean isDataSet = false; 1655 // (Re-)Evaluates fast-path status if needed. 1656 if (fastPathCheckNeeded) { 1657 isDataSet = checkAndSetFastPathStatus(); 1658 } 1659 1660 if (!isFastPath ) 1661 // DecimalFormat instance is not in a fast-path state. 1662 return null; 1663 1664 if (!Double.isFinite(d)) 1665 // Should not use fast-path for Infinity and NaN. 1666 return null; 1667 1668 // Extracts and records sign of double value, possibly changing it 1669 // to a positive one, before calling fastDoubleFormat(). 1670 boolean negative = false; 1671 if (d < 0.0d) { 1672 negative = true; 1673 d = -d; 1674 } else if (d == 0.0d) { 1675 negative = (Math.copySign(1.0d, d) == -1.0d); 1676 d = +0.0d; 1677 } 1678 1679 if (d > MAX_INT_AS_DOUBLE) 1680 // Filters out values that are outside expected fast-path range 1681 return null; 1682 else { 1683 if (!isDataSet) { 1684 /* 1685 * If the fast path data is not set through 1686 * checkAndSetFastPathStatus() and fulfil the 1687 * fast path conditions then reset the data 1688 * directly through resetFastPathData() 1689 */ 1690 resetFastPathData(isFastPath); 1691 } 1692 fastDoubleFormat(d, negative); 1693 1694 } 1695 1696 1697 // Returns a new string from updated fastPathContainer. 1698 return new String(fastPathData.fastPathContainer, 1699 fastPathData.firstUsedIndex, 1700 fastPathData.lastFreeIndex - fastPathData.firstUsedIndex); 1701 1702 } 1703 1704 /** 1705 * Sets the {@code DigitList} used by this {@code DecimalFormat} 1706 * instance. 1707 * @param number the number to format 1708 * @param isNegative true, if the number is negative; false otherwise 1709 * @param maxDigits the max digits 1710 */ 1711 void setDigitList(Number number, boolean isNegative, int maxDigits) { 1712 1713 if (number instanceof Double) { 1714 digitList.set(isNegative, (Double) number, maxDigits, true); 1715 } else if (number instanceof BigDecimal) { 1716 digitList.set(isNegative, (BigDecimal) number, maxDigits, true); 1717 } else if (number instanceof Long) { 1718 digitList.set(isNegative, (Long) number, maxDigits); 1719 } else if (number instanceof BigInteger) { 1720 digitList.set(isNegative, (BigInteger) number, maxDigits); 1721 } 1722 } 1723 1724 // ======== End fast-path formating logic for double ========================= 1725 1726 /** 1727 * Complete the formatting of a finite number. On entry, the digitList must 1728 * be filled in with the correct digits. 1729 */ 1730 private StringBuffer subformat(StringBuffer result, FieldDelegate delegate, 1731 boolean isNegative, boolean isInteger, 1732 int maxIntDigits, int minIntDigits, 1733 int maxFraDigits, int minFraDigits) { 1734 1735 // Process prefix 1736 if (isNegative) { 1737 append(result, negativePrefix, delegate, 1738 getNegativePrefixFieldPositions(), Field.SIGN); 1739 } else { 1740 append(result, positivePrefix, delegate, 1741 getPositivePrefixFieldPositions(), Field.SIGN); 1742 } 1743 1744 // Process number 1745 subformatNumber(result, delegate, isNegative, isInteger, 1746 maxIntDigits, minIntDigits, maxFraDigits, minFraDigits); 1747 1748 // Process suffix 1749 if (isNegative) { 1750 append(result, negativeSuffix, delegate, 1751 getNegativeSuffixFieldPositions(), Field.SIGN); 1752 } else { 1753 append(result, positiveSuffix, delegate, 1754 getPositiveSuffixFieldPositions(), Field.SIGN); 1755 } 1756 1757 return result; 1758 } 1759 1760 /** 1761 * Subformats number part using the {@code DigitList} of this 1762 * {@code DecimalFormat} instance. 1763 * @param result where the text is to be appended 1764 * @param delegate notified of the location of sub fields 1765 * @param isNegative true, if the number is negative; false otherwise 1766 * @param isInteger true, if the number is an integer; false otherwise 1767 * @param maxIntDigits maximum integer digits 1768 * @param minIntDigits minimum integer digits 1769 * @param maxFraDigits maximum fraction digits 1770 * @param minFraDigits minimum fraction digits 1771 */ 1772 void subformatNumber(StringBuffer result, FieldDelegate delegate, 1773 boolean isNegative, boolean isInteger, 1774 int maxIntDigits, int minIntDigits, 1775 int maxFraDigits, int minFraDigits) { 1776 1777 char grouping = symbols.getGroupingSeparator(); 1778 char zero = symbols.getZeroDigit(); 1779 int zeroDelta = zero - '0'; // '0' is the DigitList representation of zero 1780 1781 char decimal = isCurrencyFormat ? 1782 symbols.getMonetaryDecimalSeparator() : 1783 symbols.getDecimalSeparator(); 1784 1785 /* Per bug 4147706, DecimalFormat must respect the sign of numbers which 1786 * format as zero. This allows sensible computations and preserves 1787 * relations such as signum(1/x) = signum(x), where x is +Infinity or 1788 * -Infinity. Prior to this fix, we always formatted zero values as if 1789 * they were positive. Liu 7/6/98. 1790 */ 1791 if (digitList.isZero()) { 1792 digitList.decimalAt = 0; // Normalize 1793 } 1794 1795 if (useExponentialNotation) { 1796 int iFieldStart = result.length(); 1797 int iFieldEnd = -1; 1798 int fFieldStart = -1; 1799 1800 // Minimum integer digits are handled in exponential format by 1801 // adjusting the exponent. For example, 0.01234 with 3 minimum 1802 // integer digits is "123.4E-4". 1803 // Maximum integer digits are interpreted as indicating the 1804 // repeating range. This is useful for engineering notation, in 1805 // which the exponent is restricted to a multiple of 3. For 1806 // example, 0.01234 with 3 maximum integer digits is "12.34e-3". 1807 // If maximum integer digits are > 1 and are larger than 1808 // minimum integer digits, then minimum integer digits are 1809 // ignored. 1810 int exponent = digitList.decimalAt; 1811 int repeat = maxIntDigits; 1812 int minimumIntegerDigits = minIntDigits; 1813 if (repeat > 1 && repeat > minIntDigits) { 1814 // A repeating range is defined; adjust to it as follows. 1815 // If repeat == 3, we have 6,5,4=>3; 3,2,1=>0; 0,-1,-2=>-3; 1816 // -3,-4,-5=>-6, etc. This takes into account that the 1817 // exponent we have here is off by one from what we expect; 1818 // it is for the format 0.MMMMMx10^n. 1819 if (exponent >= 1) { 1820 exponent = ((exponent - 1) / repeat) * repeat; 1821 } else { 1822 // integer division rounds towards 0 1823 exponent = ((exponent - repeat) / repeat) * repeat; 1824 } 1825 minimumIntegerDigits = 1; 1826 } else { 1827 // No repeating range is defined; use minimum integer digits. 1828 exponent -= minimumIntegerDigits; 1829 } 1830 1831 // We now output a minimum number of digits, and more if there 1832 // are more digits, up to the maximum number of digits. We 1833 // place the decimal point after the "integer" digits, which 1834 // are the first (decimalAt - exponent) digits. 1835 int minimumDigits = minIntDigits + minFraDigits; 1836 if (minimumDigits < 0) { // overflow? 1837 minimumDigits = Integer.MAX_VALUE; 1838 } 1839 1840 // The number of integer digits is handled specially if the number 1841 // is zero, since then there may be no digits. 1842 int integerDigits = digitList.isZero() ? minimumIntegerDigits : 1843 digitList.decimalAt - exponent; 1844 if (minimumDigits < integerDigits) { 1845 minimumDigits = integerDigits; 1846 } 1847 int totalDigits = digitList.count; 1848 if (minimumDigits > totalDigits) { 1849 totalDigits = minimumDigits; 1850 } 1851 boolean addedDecimalSeparator = false; 1852 1853 for (int i=0; i<totalDigits; ++i) { 1854 if (i == integerDigits) { 1855 // Record field information for caller. 1856 iFieldEnd = result.length(); 1857 1858 result.append(decimal); 1859 addedDecimalSeparator = true; 1860 1861 // Record field information for caller. 1862 fFieldStart = result.length(); 1863 } 1864 result.append((i < digitList.count) ? 1865 (char)(digitList.digits[i] + zeroDelta) : 1866 zero); 1867 } 1868 1869 if (decimalSeparatorAlwaysShown && totalDigits == integerDigits) { 1870 // Record field information for caller. 1871 iFieldEnd = result.length(); 1872 1873 result.append(decimal); 1874 addedDecimalSeparator = true; 1875 1876 // Record field information for caller. 1877 fFieldStart = result.length(); 1878 } 1879 1880 // Record field information 1881 if (iFieldEnd == -1) { 1882 iFieldEnd = result.length(); 1883 } 1884 delegate.formatted(INTEGER_FIELD, Field.INTEGER, Field.INTEGER, 1885 iFieldStart, iFieldEnd, result); 1886 if (addedDecimalSeparator) { 1887 delegate.formatted(Field.DECIMAL_SEPARATOR, 1888 Field.DECIMAL_SEPARATOR, 1889 iFieldEnd, fFieldStart, result); 1890 } 1891 if (fFieldStart == -1) { 1892 fFieldStart = result.length(); 1893 } 1894 delegate.formatted(FRACTION_FIELD, Field.FRACTION, Field.FRACTION, 1895 fFieldStart, result.length(), result); 1896 1897 // The exponent is output using the pattern-specified minimum 1898 // exponent digits. There is no maximum limit to the exponent 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 1940 // number of integer digits we will display, including both 1941 // leading zeros required to satisfy getMinimumIntegerDigits, 1942 // and actual digits present in the number. 1943 int count = minIntDigits; 1944 int digitIndex = 0; // Index into digitList.fDigits[] 1945 if (digitList.decimalAt > 0 && count < digitList.decimalAt) { 1946 count = digitList.decimalAt; 1947 } 1948 1949 // Handle the case where getMaximumIntegerDigits() is smaller 1950 // than the real number of integer digits. If this is so, we 1951 // output the least significant max integer digits. For example, 1952 // the value 1997 printed with 2 max integer digits is just "97". 1953 if (count > maxIntDigits) { 1954 count = maxIntDigits; 1955 digitIndex = digitList.decimalAt - count; 1956 } 1957 1958 int sizeBeforeIntegerPart = result.length(); 1959 for (int i=count-1; i>=0; --i) { 1960 if (i < digitList.decimalAt && digitIndex < digitList.count) { 1961 // Output a real digit 1962 result.append((char)(digitList.digits[digitIndex++] + zeroDelta)); 1963 } else { 1964 // Output a leading zero 1965 result.append(zero); 1966 } 1967 1968 // Output grouping separator if necessary. Don't output a 1969 // grouping separator if i==0 though; that's at the end of 1970 // the integer part. 1971 if (isGroupingUsed() && i>0 && (groupingSize != 0) && 1972 (i % groupingSize == 0)) { 1973 int gStart = result.length(); 1974 result.append(grouping); 1975 delegate.formatted(Field.GROUPING_SEPARATOR, 1976 Field.GROUPING_SEPARATOR, gStart, 1977 result.length(), result); 1978 } 1979 } 1980 1981 // Determine whether or not there are any printable fractional 1982 // digits. If we've used up the digits we know there aren't. 1983 boolean fractionPresent = (minFraDigits > 0) || 1984 (!isInteger && digitIndex < digitList.count); 1985 1986 // If there is no fraction present, and we haven't printed any 1987 // integer digits, then print a zero. Otherwise we won't print 1988 // _any_ digits, and we won't be able to parse this string. 1989 if (!fractionPresent && result.length() == sizeBeforeIntegerPart) { 1990 result.append(zero); 1991 } 1992 1993 delegate.formatted(INTEGER_FIELD, Field.INTEGER, Field.INTEGER, 1994 iFieldStart, result.length(), result); 1995 1996 // Output the decimal separator if we always do so. 1997 int sStart = result.length(); 1998 if (decimalSeparatorAlwaysShown || fractionPresent) { 1999 result.append(decimal); 2000 } 2001 2002 if (sStart != result.length()) { 2003 delegate.formatted(Field.DECIMAL_SEPARATOR, 2004 Field.DECIMAL_SEPARATOR, 2005 sStart, result.length(), result); 2006 } 2007 int fFieldStart = result.length(); 2008 2009 for (int i=0; i < maxFraDigits; ++i) { 2010 // Here is where we escape from the loop. We escape if we've 2011 // output the maximum fraction digits (specified in the for 2012 // expression above). 2013 // We also stop when we've output the minimum digits and either: 2014 // we have an integer, so there is no fractional stuff to 2015 // display, or we're out of significant digits. 2016 if (i >= minFraDigits && 2017 (isInteger || digitIndex >= digitList.count)) { 2018 break; 2019 } 2020 2021 // Output leading fractional zeros. These are zeros that come 2022 // after the decimal but before any significant digits. These 2023 // are only output if abs(number being formatted) < 1.0. 2024 if (-1-i > (digitList.decimalAt-1)) { 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); 2155 } 2156 } 2157 2158 if (multiplier == 0) { 2159 if (digitList.isZero()) { 2160 return Double.valueOf(Double.NaN); 2161 } else if (status[STATUS_POSITIVE]) { 2162 return Double.valueOf(Double.POSITIVE_INFINITY); 2163 } else { 2164 return Double.valueOf(Double.NEGATIVE_INFINITY); 2165 } 2166 } 2167 2168 if (isParseBigDecimal()) { 2169 BigDecimal bigDecimalResult = digitList.getBigDecimal(); 2170 2171 if (multiplier != 1) { 2172 try { 2173 bigDecimalResult = bigDecimalResult.divide(getBigDecimalMultiplier()); 2174 } 2175 catch (ArithmeticException e) { // non-terminating decimal expansion 2176 bigDecimalResult = bigDecimalResult.divide(getBigDecimalMultiplier(), roundingMode); 2177 } 2178 } 2179 2180 if (!status[STATUS_POSITIVE]) { 2181 bigDecimalResult = bigDecimalResult.negate(); 2182 } 2183 return bigDecimalResult; 2184 } else { 2185 boolean gotDouble = true; 2186 boolean gotLongMinimum = false; 2187 double doubleResult = 0.0; 2188 long longResult = 0; 2189 2190 // Finally, have DigitList parse the digits into a value. 2191 if (digitList.fitsIntoLong(status[STATUS_POSITIVE], isParseIntegerOnly())) { 2192 gotDouble = false; 2193 longResult = digitList.getLong(); 2194 if (longResult < 0) { // got Long.MIN_VALUE 2195 gotLongMinimum = true; 2196 } 2197 } else { 2198 doubleResult = digitList.getDouble(); 2199 } 2200 2201 // Divide by multiplier. We have to be careful here not to do 2202 // unneeded conversions between double and long. 2203 if (multiplier != 1) { 2204 if (gotDouble) { 2205 doubleResult /= multiplier; 2206 } else { 2207 // Avoid converting to double if we can 2208 if (longResult % multiplier == 0) { 2209 longResult /= multiplier; 2210 } else { 2211 doubleResult = ((double)longResult) / multiplier; 2212 gotDouble = true; 2213 } 2214 } 2215 } 2216 2217 if (!status[STATUS_POSITIVE] && !gotLongMinimum) { 2218 doubleResult = -doubleResult; 2219 longResult = -longResult; 2220 } 2221 2222 // At this point, if we divided the result by the multiplier, the 2223 // result may fit into a long. We check for this case and return 2224 // a long if possible. 2225 // We must do this AFTER applying the negative (if appropriate) 2226 // in order to handle the case of LONG_MIN; otherwise, if we do 2227 // this with a positive value -LONG_MIN, the double is > 0, but 2228 // the long is < 0. We also must retain a double in the case of 2229 // -0.0, which will compare as == to a long 0 cast to a double 2230 // (bug 4162852). 2231 if (multiplier != 1 && gotDouble) { 2232 longResult = (long)doubleResult; 2233 gotDouble = ((doubleResult != (double)longResult) || 2234 (doubleResult == 0.0 && 1/doubleResult < 0.0)) && 2235 !isParseIntegerOnly(); 2236 } 2237 2238 // cast inside of ?: because of binary numeric promotion, JLS 15.25 2239 return gotDouble ? (Number)doubleResult : (Number)longResult; 2240 } 2241 } 2242 2243 /** 2244 * Return a BigInteger multiplier. 2245 */ 2246 private BigInteger getBigIntegerMultiplier() { 2247 if (bigIntegerMultiplier == null) { 2248 bigIntegerMultiplier = BigInteger.valueOf(multiplier); 2249 } 2250 return bigIntegerMultiplier; 2251 } 2252 private transient BigInteger bigIntegerMultiplier; 2253 2254 /** 2255 * Return a BigDecimal multiplier. 2256 */ 2257 private BigDecimal getBigDecimalMultiplier() { 2258 if (bigDecimalMultiplier == null) { 2259 bigDecimalMultiplier = new BigDecimal(multiplier); 2260 } 2261 return bigDecimalMultiplier; 2262 } 2263 private transient BigDecimal bigDecimalMultiplier; 2264 2265 private static final int STATUS_INFINITE = 0; 2266 private static final int STATUS_POSITIVE = 1; 2267 private static final int STATUS_LENGTH = 2; 2268 2269 /** 2270 * Parse the given text into a number. The text is parsed beginning at 2271 * parsePosition, until an unparseable character is seen. 2272 * @param text The string to parse. 2273 * @param parsePosition The position at which to being parsing. Upon 2274 * return, the first unparseable character. 2275 * @param digits The DigitList to set to the parsed value. 2276 * @param isExponent If true, parse an exponent. This means no 2277 * infinite values and integer only. 2278 * @param status Upon return contains boolean status flags indicating 2279 * whether the value was infinite and whether it was positive. 2280 */ 2281 private final boolean subparse(String text, ParsePosition parsePosition, 2282 String positivePrefix, String negativePrefix, 2283 DigitList digits, boolean isExponent, 2284 boolean status[]) { 2285 int position = parsePosition.index; 2286 int oldStart = parsePosition.index; 2287 boolean gotPositive, gotNegative; 2288 2289 // check for positivePrefix; take longest 2290 gotPositive = text.regionMatches(position, positivePrefix, 0, 2291 positivePrefix.length()); 2292 gotNegative = text.regionMatches(position, negativePrefix, 0, 2293 negativePrefix.length()); 2294 2295 if (gotPositive && gotNegative) { 2296 if (positivePrefix.length() > negativePrefix.length()) { 2297 gotNegative = false; 2298 } else if (positivePrefix.length() < negativePrefix.length()) { 2299 gotPositive = false; 2300 } 2301 } 2302 2303 if (gotPositive) { 2304 position += positivePrefix.length(); 2305 } else if (gotNegative) { 2306 position += negativePrefix.length(); 2307 } else { 2308 parsePosition.errorIndex = position; 2309 return false; 2310 } 2311 2312 position = subparseNumber(text, position, digits, true, isExponent, status); 2313 if (position == -1) { 2314 parsePosition.index = oldStart; 2315 parsePosition.errorIndex = oldStart; 2316 return false; 2317 } 2318 2319 // Check for suffix 2320 if (!isExponent) { 2321 if (gotPositive) { 2322 gotPositive = text.regionMatches(position,positiveSuffix,0, 2323 positiveSuffix.length()); 2324 } 2325 if (gotNegative) { 2326 gotNegative = text.regionMatches(position,negativeSuffix,0, 2327 negativeSuffix.length()); 2328 } 2329 2330 // If both match, take longest 2331 if (gotPositive && gotNegative) { 2332 if (positiveSuffix.length() > negativeSuffix.length()) { 2333 gotNegative = false; 2334 } else if (positiveSuffix.length() < negativeSuffix.length()) { 2335 gotPositive = false; 2336 } 2337 } 2338 2339 // Fail if neither or both 2340 if (gotPositive == gotNegative) { 2341 parsePosition.errorIndex = position; 2342 return false; 2343 } 2344 2345 parsePosition.index = position + 2346 (gotPositive ? positiveSuffix.length() : negativeSuffix.length()); // mark success! 2347 } else { 2348 parsePosition.index = position; 2349 } 2350 2351 status[STATUS_POSITIVE] = gotPositive; 2352 if (parsePosition.index == oldStart) { 2353 parsePosition.errorIndex = position; 2354 return false; 2355 } 2356 return true; 2357 } 2358 2359 /** 2360 * Parses a number from the given {@code text}. The text is parsed 2361 * beginning at position, until an unparseable character is seen. 2362 * 2363 * @param text the string to parse 2364 * @param position the position at which parsing begins 2365 * @param digits the DigitList to set to the parsed value 2366 * @param checkExponent whether to check for exponential number 2367 * @param isExponent if the exponential part is encountered 2368 * @param status upon return contains boolean status flags indicating 2369 * whether the value is infinite and whether it is 2370 * positive 2371 * @return returns the position of the first unparseable character or 2372 * -1 in case of no valid number parsed 2373 */ 2374 int subparseNumber(String text, int position, 2375 DigitList digits, boolean checkExponent, 2376 boolean isExponent, boolean status[]) { 2377 // process digits or Inf, find decimal position 2378 status[STATUS_INFINITE] = false; 2379 if (!isExponent && text.regionMatches(position,symbols.getInfinity(),0, 2380 symbols.getInfinity().length())) { 2381 position += symbols.getInfinity().length(); 2382 status[STATUS_INFINITE] = true; 2383 } else { 2384 // We now have a string of digits, possibly with grouping symbols, 2385 // and decimal points. We want to process these into a DigitList. 2386 // We don't want to put a bunch of leading zeros into the DigitList 2387 // though, so we keep track of the location of the decimal point, 2388 // put only significant digits into the DigitList, and adjust the 2389 // exponent as needed. 2390 2391 digits.decimalAt = digits.count = 0; 2392 char zero = symbols.getZeroDigit(); 2393 char decimal = isCurrencyFormat ? 2394 symbols.getMonetaryDecimalSeparator() : 2395 symbols.getDecimalSeparator(); 2396 char grouping = symbols.getGroupingSeparator(); 2397 String exponentString = symbols.getExponentSeparator(); 2398 boolean sawDecimal = false; 2399 boolean sawExponent = false; 2400 boolean sawDigit = false; 2401 int exponent = 0; // Set to the exponent value, if any 2402 2403 // We have to track digitCount ourselves, because digits.count will 2404 // pin when the maximum allowable digits is reached. 2405 int digitCount = 0; 2406 2407 int backup = -1; 2408 for (; position < text.length(); ++position) { 2409 char ch = text.charAt(position); 2410 2411 /* We recognize all digit ranges, not only the Latin digit range 2412 * '0'..'9'. We do so by using the Character.digit() method, 2413 * which converts a valid Unicode digit to the range 0..9. 2414 * 2415 * The character 'ch' may be a digit. If so, place its value 2416 * from 0 to 9 in 'digit'. First try using the locale digit, 2417 * which may or MAY NOT be a standard Unicode digit range. If 2418 * this fails, try using the standard Unicode digit ranges by 2419 * calling Character.digit(). If this also fails, digit will 2420 * have a value outside the range 0..9. 2421 */ 2422 int digit = ch - zero; 2423 if (digit < 0 || digit > 9) { 2424 digit = Character.digit(ch, 10); 2425 } 2426 2427 if (digit == 0) { 2428 // Cancel out backup setting (see grouping handler below) 2429 backup = -1; // Do this BEFORE continue statement below!!! 2430 sawDigit = true; 2431 2432 // Handle leading zeros 2433 if (digits.count == 0) { 2434 // Ignore leading zeros in integer part of number. 2435 if (!sawDecimal) { 2436 continue; 2437 } 2438 2439 // If we have seen the decimal, but no significant 2440 // digits yet, then we account for leading zeros by 2441 // decrementing the digits.decimalAt into negative 2442 // values. 2443 --digits.decimalAt; 2444 } else { 2445 ++digitCount; 2446 digits.append((char)(digit + '0')); 2447 } 2448 } else if (digit > 0 && digit <= 9) { // [sic] digit==0 handled above 2449 sawDigit = true; 2450 ++digitCount; 2451 digits.append((char)(digit + '0')); 2452 2453 // Cancel out backup setting (see grouping handler below) 2454 backup = -1; 2455 } else if (!isExponent && ch == decimal) { 2456 // If we're only parsing integers, or if we ALREADY saw the 2457 // decimal, then don't parse this one. 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) { 2499 digits.decimalAt = digitCount; // Not digits.count! 2500 } 2501 2502 // Adjust for exponent, if any 2503 digits.decimalAt += exponent; 2504 2505 // If none of the text string was recognized. For example, parse 2506 // "x" with pattern "#0.00" (return index and error index both 0) 2507 // parse "$" with pattern "$#0.00". (return index 0 and error 2508 // index 1). 2509 if (!sawDigit && digitCount == 0) { 2510 return -1; 2511 } 2512 } 2513 return position; 2514 2515 } 2516 2517 /** 2518 * Returns a copy of the decimal format symbols, which is generally not 2519 * changed by the programmer or user. 2520 * @return a copy of the desired DecimalFormatSymbols 2521 * @see java.text.DecimalFormatSymbols 2522 */ 2523 public DecimalFormatSymbols getDecimalFormatSymbols() { 2524 try { 2525 // don't allow multiple references 2526 return (DecimalFormatSymbols) symbols.clone(); 2527 } catch (Exception foo) { 2528 return null; // should never happen 2529 } 2530 } 2531 2532 2533 /** 2534 * Sets the decimal format symbols, which is generally not changed 2535 * by the programmer or user. 2536 * @param newSymbols desired DecimalFormatSymbols 2537 * @see java.text.DecimalFormatSymbols 2538 */ 2539 public void setDecimalFormatSymbols(DecimalFormatSymbols newSymbols) { 2540 try { 2541 // don't allow multiple references 2542 symbols = (DecimalFormatSymbols) newSymbols.clone(); 2543 expandAffixes(); 2544 fastPathCheckNeeded = true; 2545 } catch (Exception foo) { 2546 // should never happen 2547 } 2548 } 2549 2550 /** 2551 * Get the positive prefix. 2552 * <P>Examples: +123, $123, sFr123 2553 * 2554 * @return the positive prefix 2555 */ 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 2720 * @see #setMultiplier(int) 2721 */ 2722 public int getMultiplier () { 2723 return multiplier; 2724 } 2725 2726 /** 2727 * Sets the multiplier for use in percent, per mille, and similar 2728 * formats. 2729 * For a percent format, set the multiplier to 100 and the suffixes to 2730 * have '%' (for Arabic, use the Arabic percent sign). 2731 * For a per mille format, set the multiplier to 1000 and the suffixes to 2732 * have '\u2030'. 2733 * 2734 * <P>Example: with multiplier 100, 1.23 is formatted as "123", and 2735 * "123" is parsed into 1.23. 2736 * 2737 * @param newValue the new multiplier 2738 * @see #getMultiplier 2739 */ 2740 public void setMultiplier (int newValue) { 2741 multiplier = newValue; 2742 bigDecimalMultiplier = null; 2743 bigIntegerMultiplier = null; 2744 fastPathCheckNeeded = true; 2745 } 2746 2747 /** 2748 * {@inheritDoc} 2749 */ 2750 @Override 2751 public void setGroupingUsed(boolean newValue) { 2752 super.setGroupingUsed(newValue); 2753 fastPathCheckNeeded = true; 2754 } 2755 2756 /** 2757 * Return the grouping size. Grouping size is the number of digits between 2758 * grouping separators in the integer portion of a number. For example, 2759 * in the number "123,456.78", the grouping size is 3. 2760 * 2761 * @return the grouping size 2762 * @see #setGroupingSize 2763 * @see java.text.NumberFormat#isGroupingUsed 2764 * @see java.text.DecimalFormatSymbols#getGroupingSeparator 2765 */ 2766 public int getGroupingSize () { 2767 return groupingSize; 2768 } 2769 2770 /** 2771 * Set the grouping size. Grouping size is the number of digits between 2772 * grouping separators in the integer portion of a number. For example, 2773 * in the number "123,456.78", the grouping size is 3. 2774 * <br> 2775 * The value passed in is converted to a byte, which may lose information. 2776 * 2777 * @param newValue the new grouping size 2778 * @see #getGroupingSize 2779 * @see java.text.NumberFormat#setGroupingUsed 2780 * @see java.text.DecimalFormatSymbols#setGroupingSeparator 2781 */ 2782 public void setGroupingSize (int newValue) { 2783 groupingSize = (byte)newValue; 2784 fastPathCheckNeeded = true; 2785 } 2786 2787 /** 2788 * Allows you to get the behavior of the decimal separator with integers. 2789 * (The decimal separator will always appear with decimals.) 2790 * <P>Example: Decimal ON: 12345 → 12345.; OFF: 12345 → 12345 2791 * 2792 * @return {@code true} if the decimal separator is always shown; 2793 * {@code false} otherwise 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 2848 // isFastPath flag. In addition fastPathCheckNeeded is a sentinel flag 2849 // that forces recalculation of all fast-path fields when set to true. 2850 // 2851 // There is thus no need to clone all the fast-path fields. 2852 // We just only need to set fastPathCheckNeeded to true when cloning, 2853 // and init fastPathData to null as if it were a truly new instance. 2854 // Every fast-path field will be recalculated (only once) at next usage of 2855 // fast-path algorithm. 2856 other.fastPathCheckNeeded = true; 2857 other.isFastPath = false; 2858 other.fastPathData = null; 2859 2860 return other; 2861 } 2862 2863 /** 2864 * Overrides equals 2865 */ 2866 @Override 2867 public boolean equals(Object obj) 2868 { 2869 if (obj == null) 2870 return false; 2871 if (!super.equals(obj)) 2872 return false; // super does class check 2873 DecimalFormat other = (DecimalFormat) obj; 2874 return ((posPrefixPattern == other.posPrefixPattern && 2875 positivePrefix.equals(other.positivePrefix)) 2876 || (posPrefixPattern != null && 2877 posPrefixPattern.equals(other.posPrefixPattern))) 2878 && ((posSuffixPattern == other.posSuffixPattern && 2879 positiveSuffix.equals(other.positiveSuffix)) 2880 || (posSuffixPattern != null && 2881 posSuffixPattern.equals(other.posSuffixPattern))) 2882 && ((negPrefixPattern == other.negPrefixPattern && 2883 negativePrefix.equals(other.negativePrefix)) 2884 || (negPrefixPattern != null && 2885 negPrefixPattern.equals(other.negPrefixPattern))) 2886 && ((negSuffixPattern == other.negSuffixPattern && 2887 negativeSuffix.equals(other.negativeSuffix)) 2888 || (negSuffixPattern != null && 2889 negSuffixPattern.equals(other.negSuffixPattern))) 2890 && multiplier == other.multiplier 2891 && groupingSize == other.groupingSize 2892 && decimalSeparatorAlwaysShown == other.decimalSeparatorAlwaysShown 2893 && parseBigDecimal == other.parseBigDecimal 2894 && useExponentialNotation == other.useExponentialNotation 2895 && (!useExponentialNotation || 2896 minExponentDigits == other.minExponentDigits) 2897 && maximumIntegerDigits == other.maximumIntegerDigits 2898 && minimumIntegerDigits == other.minimumIntegerDigits 2899 && maximumFractionDigits == other.maximumFractionDigits 2900 && minimumFractionDigits == other.minimumFractionDigits 2901 && roundingMode == other.roundingMode 2902 && symbols.equals(other.symbols); 2903 } 2904 2905 /** 2906 * Overrides hashCode 2907 */ 2908 @Override 2909 public int hashCode() { 2910 return super.hashCode() * 37 + positivePrefix.hashCode(); 2911 // just enough fields for a reasonable distribution 2912 } 2913 2914 /** 2915 * Synthesizes a pattern string that represents the current state 2916 * of this Format object. 2917 * 2918 * @return a pattern string 2919 * @see #applyPattern 2920 */ 2921 public String toPattern() { 2922 return toPattern( false ); 2923 } 2924 2925 /** 2926 * Synthesizes a localized pattern string that represents the current 2927 * state of this Format object. 2928 * 2929 * @return a localized pattern string 2930 * @see #applyPattern 2931 */ 2932 public String toLocalizedPattern() { 2933 return toPattern( true ); 2934 } 2935 2936 /** 2937 * Expand the affix pattern strings into the expanded affix strings. If any 2938 * affix pattern string is null, do not expand it. This method should be 2939 * called any time the symbols or the affix patterns change in order to keep 2940 * the expanded affix strings up to date. 2941 */ 2942 private void expandAffixes() { 2943 // Reuse one StringBuffer for better performance 2944 StringBuffer buffer = new StringBuffer(); 2945 if (posPrefixPattern != null) { 2946 positivePrefix = expandAffix(posPrefixPattern, buffer); 2947 positivePrefixFieldPositions = null; 2948 } 2949 if (posSuffixPattern != null) { 2950 positiveSuffix = expandAffix(posSuffixPattern, buffer); 2951 positiveSuffixFieldPositions = null; 2952 } 2953 if (negPrefixPattern != null) { 2954 negativePrefix = expandAffix(negPrefixPattern, buffer); 2955 negativePrefixFieldPositions = null; 2956 } 2957 if (negSuffixPattern != null) { 2958 negativeSuffix = expandAffix(negSuffixPattern, buffer); 2959 negativeSuffixFieldPositions = null; 2960 } 2961 } 2962 2963 /** 2964 * Expand an affix pattern into an affix string. All characters in the 2965 * pattern are literal unless prefixed by QUOTE. The following characters 2966 * after QUOTE are recognized: PATTERN_PERCENT, PATTERN_PER_MILLE, 2967 * PATTERN_MINUS, and CURRENCY_SIGN. If CURRENCY_SIGN is doubled (QUOTE + 2968 * CURRENCY_SIGN + CURRENCY_SIGN), it is interpreted as an ISO 4217 2969 * currency code. Any other character after a QUOTE represents itself. 2970 * QUOTE must be followed by another character; QUOTE may not occur by 2971 * itself at the end of the pattern. 2972 * 2973 * @param pattern the non-null, possibly empty pattern 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. 3098 * Ignored unless affixPattern is null. If affixPattern is null, then 3099 * expAffix is appended as a literal affix. 3100 * @param localized true if the appended pattern should contain localized 3101 * pattern characters; otherwise, non-localized pattern chars are appended 3102 */ 3103 private void appendAffix(StringBuffer buffer, String affixPattern, 3104 String expAffix, boolean localized) { 3105 if (affixPattern == null) { 3106 appendAffix(buffer, expAffix, localized); 3107 } else { 3108 int i; 3109 for (int pos=0; pos<affixPattern.length(); pos=i) { 3110 i = affixPattern.indexOf(QUOTE, pos); 3111 if (i < 0) { 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 } 3183 } 3184 if (needQuote) buffer.append('\''); 3185 } 3186 3187 /** 3188 * Does the real work of generating a pattern. */ 3189 private String toPattern(boolean localized) { 3190 StringBuffer result = new StringBuffer(); 3191 for (int j = 1; j >= 0; --j) { 3192 if (j == 1) 3193 appendAffix(result, posPrefixPattern, positivePrefix, localized); 3194 else appendAffix(result, negPrefixPattern, negativePrefix, localized); 3195 int i; 3196 int digitCount = useExponentialNotation 3197 ? getMaximumIntegerDigits() 3198 : Math.max(groupingSize, getMinimumIntegerDigits())+1; 3199 for (i = digitCount; i > 0; --i) { 3200 if (i != digitCount && isGroupingUsed() && groupingSize != 0 && 3201 i % groupingSize == 0) { 3202 result.append(localized ? symbols.getGroupingSeparator() : 3203 PATTERN_GROUPING_SEPARATOR); 3204 } 3205 result.append(i <= getMinimumIntegerDigits() 3206 ? (localized ? symbols.getZeroDigit() : PATTERN_ZERO_DIGIT) 3207 : (localized ? symbols.getDigit() : PATTERN_DIGIT)); 3208 } 3209 if (getMaximumFractionDigits() > 0 || decimalSeparatorAlwaysShown) 3210 result.append(localized ? symbols.getDecimalSeparator() : 3211 PATTERN_DECIMAL_SEPARATOR); 3212 for (i = 0; i < getMaximumFractionDigits(); ++i) { 3213 if (i < getMinimumFractionDigits()) { 3214 result.append(localized ? symbols.getZeroDigit() : 3215 PATTERN_ZERO_DIGIT); 3216 } else { 3217 result.append(localized ? symbols.getDigit() : 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) { 3315 zeroDigit = symbols.getZeroDigit(); 3316 groupingSeparator = symbols.getGroupingSeparator(); 3317 decimalSeparator = symbols.getDecimalSeparator(); 3318 percent = symbols.getPercent(); 3319 perMill = symbols.getPerMill(); 3320 digit = symbols.getDigit(); 3321 separator = symbols.getPatternSeparator(); 3322 exponent = symbols.getExponentSeparator(); 3323 minus = symbols.getMinusSign(); 3324 } 3325 boolean gotNegative = false; 3326 decimalSeparatorAlwaysShown = false; 3327 isCurrencyFormat = false; 3328 useExponentialNotation = false; 3329 3330 int start = 0; 3331 for (int j = 1; j >= 0 && start < pattern.length(); --j) { 3332 boolean inQuote = false; 3333 StringBuffer prefix = new StringBuffer(); 3334 StringBuffer suffix = new StringBuffer(); 3335 int decimalPos = -1; 3336 int multiplier = 1; 3337 int digitLeftCount = 0, zeroDigitCount = 0, digitRightCount = 0; 3338 byte groupingCount = -1; 3339 3340 // The phase ranges from 0 to 2. Phase 0 is the prefix. Phase 1 is 3341 // the section of the pattern with digits, decimal separator, 3342 // grouping characters. Phase 2 is the suffix. In phases 0 and 2, 3343 // percent, per mille, and currency symbols are recognized and 3344 // translated. The separation of the characters into phases is 3345 // strictly enforced; if phase 1 characters are to appear in the 3346 // suffix, for example, they must be quoted. 3347 int phase = 0; 3348 3349 // The affix is either the prefix or the suffix. 3350 StringBuffer affix = prefix; 3351 3352 for (int pos = start; pos < pattern.length(); ++pos) { 3353 char ch = pattern.charAt(pos); 3354 switch (phase) { 3355 case 0: 3356 case 2: 3357 // Process the prefix / suffix characters 3358 if (inQuote) { 3359 // A quote within quotes indicates either the closing 3360 // quote or two quotes, which is a quote literal. That 3361 // is, we have the second quote in 'do' or 'don''t'. 3362 if (ch == QUOTE) { 3363 if ((pos+1) < pattern.length() && 3364 pattern.charAt(pos+1) == QUOTE) { 3365 ++pos; 3366 affix.append("''"); // 'don''t' 3367 } else { 3368 inQuote = false; // 'do' 3369 } 3370 continue; 3371 } 3372 } else { 3373 // Process unquoted characters seen in prefix or suffix 3374 // phase. 3375 if (ch == digit || 3376 ch == zeroDigit || 3377 ch == groupingSeparator || 3378 ch == decimalSeparator) { 3379 phase = 1; 3380 --pos; // Reprocess this character 3381 continue; 3382 } else if (ch == CURRENCY_SIGN) { 3383 // Use lookahead to determine if the currency sign 3384 // is doubled or not. 3385 boolean doubled = (pos + 1) < pattern.length() && 3386 pattern.charAt(pos + 1) == CURRENCY_SIGN; 3387 if (doubled) { // Skip over the doubled character 3388 ++pos; 3389 } 3390 isCurrencyFormat = true; 3391 affix.append(doubled ? "'\u00A4\u00A4" : "'\u00A4"); 3392 continue; 3393 } else if (ch == QUOTE) { 3394 // A quote outside quotes indicates either the 3395 // opening quote or two quotes, which is a quote 3396 // literal. That is, we have the first quote in 'do' 3397 // or o''clock. 3398 if (ch == QUOTE) { 3399 if ((pos+1) < pattern.length() && 3400 pattern.charAt(pos+1) == QUOTE) { 3401 ++pos; 3402 affix.append("''"); // o''clock 3403 } else { 3404 inQuote = true; // 'do' 3405 } 3406 continue; 3407 } 3408 } else if (ch == separator) { 3409 // Don't allow separators before we see digit 3410 // characters of phase 1, and don't allow separators 3411 // in the second pattern (j == 0). 3412 if (phase == 0 || j == 0) { 3413 throw new IllegalArgumentException("Unquoted special character '" + 3414 ch + "' in pattern \"" + pattern + '"'); 3415 } 3416 start = pos + 1; 3417 pos = pattern.length(); 3418 continue; 3419 } 3420 3421 // Next handle characters which are appended directly. 3422 else if (ch == percent) { 3423 if (multiplier != 1) { 3424 throw new IllegalArgumentException("Too many percent/per mille characters in pattern \"" + 3425 pattern + '"'); 3426 } 3427 multiplier = 100; 3428 affix.append("'%"); 3429 continue; 3430 } else if (ch == perMill) { 3431 if (multiplier != 1) { 3432 throw new IllegalArgumentException("Too many percent/per mille characters in pattern \"" + 3433 pattern + '"'); 3434 } 3435 multiplier = 1000; 3436 affix.append("'\u2030"); 3437 continue; 3438 } else if (ch == minus) { 3439 affix.append("'-"); 3440 continue; 3441 } 3442 } 3443 // Note that if we are within quotes, or if this is an 3444 // unquoted, non-special character, then we usually fall 3445 // through to here. 3446 affix.append(ch); 3447 break; 3448 3449 case 1: 3450 // The negative subpattern (j = 0) serves only to specify the 3451 // negative prefix and suffix, so all the phase 1 characters 3452 // e.g. digits, zeroDigit, groupingSeparator, 3453 // decimalSeparator, exponent are ignored 3454 if (j == 0) { 3455 while (pos < pattern.length()) { 3456 char negPatternChar = pattern.charAt(pos); 3457 if (negPatternChar == digit 3458 || negPatternChar == zeroDigit 3459 || negPatternChar == groupingSeparator 3460 || negPatternChar == decimalSeparator) { 3461 ++pos; 3462 } else if (pattern.regionMatches(pos, exponent, 3463 0, exponent.length())) { 3464 pos = pos + exponent.length(); 3465 } else { 3466 // Not a phase 1 character, consider it as 3467 // suffix and parse it in phase 2 3468 --pos; //process it again in outer loop 3469 phase = 2; 3470 affix = suffix; 3471 break; 3472 } 3473 } 3474 continue; 3475 } 3476 3477 // Process the digits, decimal, and grouping characters. We 3478 // record five pieces of information. We expect the digits 3479 // to occur in the pattern ####0000.####, and we record the 3480 // number of left digits, zero (central) digits, and right 3481 // digits. The position of the last grouping character is 3482 // recorded (should be somewhere within the first two blocks 3483 // of characters), as is the position of the decimal point, 3484 // if any (should be in the zero digits). If there is no 3485 // decimal point, then there should be no right digits. 3486 if (ch == digit) { 3487 if (zeroDigitCount > 0) { 3488 ++digitRightCount; 3489 } else { 3490 ++digitLeftCount; 3491 } 3492 if (groupingCount >= 0 && decimalPos < 0) { 3493 ++groupingCount; 3494 } 3495 } else if (ch == zeroDigit) { 3496 if (digitRightCount > 0) { 3497 throw new IllegalArgumentException("Unexpected '0' in pattern \"" + 3498 pattern + '"'); 3499 } 3500 ++zeroDigitCount; 3501 if (groupingCount >= 0 && decimalPos < 0) { 3502 ++groupingCount; 3503 } 3504 } else if (ch == groupingSeparator) { 3505 groupingCount = 0; 3506 } else if (ch == decimalSeparator) { 3507 if (decimalPos >= 0) { 3508 throw new IllegalArgumentException("Multiple decimal separators in pattern \"" + 3509 pattern + '"'); 3510 } 3511 decimalPos = digitLeftCount + zeroDigitCount + digitRightCount; 3512 } else if (pattern.regionMatches(pos, exponent, 0, exponent.length())){ 3513 if (useExponentialNotation) { 3514 throw new IllegalArgumentException("Multiple exponential " + 3515 "symbols in pattern \"" + pattern + '"'); 3516 } 3517 useExponentialNotation = true; 3518 minExponentDigits = 0; 3519 3520 // Use lookahead to parse out the exponential part 3521 // of the pattern, then jump into phase 2. 3522 pos = pos+exponent.length(); 3523 while (pos < pattern.length() && 3524 pattern.charAt(pos) == zeroDigit) { 3525 ++minExponentDigits; 3526 ++pos; 3527 } 3528 3529 if ((digitLeftCount + zeroDigitCount) < 1 || 3530 minExponentDigits < 1) { 3531 throw new IllegalArgumentException("Malformed exponential " + 3532 "pattern \"" + pattern + '"'); 3533 } 3534 3535 // Transition to phase 2 3536 phase = 2; 3537 affix = suffix; 3538 --pos; 3539 continue; 3540 } else { 3541 phase = 2; 3542 affix = suffix; 3543 --pos; 3544 continue; 3545 } 3546 break; 3547 } 3548 } 3549 3550 // Handle patterns with no '0' pattern character. These patterns 3551 // are legal, but must be interpreted. "##.###" -> "#0.###". 3552 // ".###" -> ".0##". 3553 /* We allow patterns of the form "####" to produce a zeroDigitCount 3554 * of zero (got that?); although this seems like it might make it 3555 * possible for format() to produce empty strings, format() checks 3556 * for this condition and outputs a zero digit in this situation. 3557 * Having a zeroDigitCount of zero yields a minimum integer digits 3558 * of zero, which allows proper round-trip patterns. That is, we 3559 * don't want "#" to become "#0" when toPattern() is called (even 3560 * though that's what it really is, semantically). 3561 */ 3562 if (zeroDigitCount == 0 && digitLeftCount > 0 && decimalPos >= 0) { 3563 // Handle "###.###" and "###." and ".###" 3564 int n = decimalPos; 3565 if (n == 0) { // Handle ".###" 3566 ++n; 3567 } 3568 digitRightCount = digitLeftCount - n; 3569 digitLeftCount = n - 1; 3570 zeroDigitCount = 1; 3571 } 3572 3573 // Do syntax checking on the digits. 3574 if ((decimalPos < 0 && digitRightCount > 0) || 3575 (decimalPos >= 0 && (decimalPos < digitLeftCount || 3576 decimalPos > (digitLeftCount + zeroDigitCount))) || 3577 groupingCount == 0 || inQuote) { 3578 throw new IllegalArgumentException("Malformed pattern \"" + 3579 pattern + '"'); 3580 } 3581 3582 if (j == 1) { 3583 posPrefixPattern = prefix.toString(); 3584 posSuffixPattern = suffix.toString(); 3585 negPrefixPattern = posPrefixPattern; // assume these for now 3586 negSuffixPattern = posSuffixPattern; 3587 int digitTotalCount = digitLeftCount + zeroDigitCount + digitRightCount; 3588 /* The effectiveDecimalPos is the position the decimal is at or 3589 * would be at if there is no decimal. Note that if decimalPos<0, 3590 * then digitTotalCount == digitLeftCount + zeroDigitCount. 3591 */ 3592 int effectiveDecimalPos = decimalPos >= 0 ? 3593 decimalPos : digitTotalCount; 3594 setMinimumIntegerDigits(effectiveDecimalPos - digitLeftCount); 3595 setMaximumIntegerDigits(useExponentialNotation ? 3596 digitLeftCount + getMinimumIntegerDigits() : 3597 MAXIMUM_INTEGER_DIGITS); 3598 setMaximumFractionDigits(decimalPos >= 0 ? 3599 (digitTotalCount - decimalPos) : 0); 3600 setMinimumFractionDigits(decimalPos >= 0 ? 3601 (digitLeftCount + zeroDigitCount - decimalPos) : 0); 3602 setGroupingUsed(groupingCount > 0); 3603 this.groupingSize = (groupingCount > 0) ? groupingCount : 0; 3604 this.multiplier = multiplier; 3605 setDecimalSeparatorAlwaysShown(decimalPos == 0 || 3606 decimalPos == digitTotalCount); 3607 } else { 3608 negPrefixPattern = prefix.toString(); 3609 negSuffixPattern = suffix.toString(); 3610 gotNegative = true; 3611 } 3612 } 3613 3614 if (pattern.isEmpty()) { 3615 posPrefixPattern = posSuffixPattern = ""; 3616 setMinimumIntegerDigits(0); 3617 setMaximumIntegerDigits(MAXIMUM_INTEGER_DIGITS); 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 } 3900 3901 // We only need to check the maximum counts because NumberFormat 3902 // .readObject has already ensured that the maximum is greater than the 3903 // minimum count. 3904 if (super.getMaximumIntegerDigits() > DOUBLE_INTEGER_DIGITS || 3905 super.getMaximumFractionDigits() > DOUBLE_FRACTION_DIGITS) { 3906 throw new InvalidObjectException("Digit count out of range"); 3907 } 3908 if (serialVersionOnStream < 3) { 3909 setMaximumIntegerDigits(super.getMaximumIntegerDigits()); 3910 setMinimumIntegerDigits(super.getMinimumIntegerDigits()); 3911 setMaximumFractionDigits(super.getMaximumFractionDigits()); 3912 setMinimumFractionDigits(super.getMinimumFractionDigits()); 3913 } 3914 if (serialVersionOnStream < 1) { 3915 // Didn't have exponential fields 3916 useExponentialNotation = false; 3917 } 3918 serialVersionOnStream = currentSerialVersion; 3919 } 3920 3921 //---------------------------------------------------------------------- 3922 // INSTANCE VARIABLES 3923 //---------------------------------------------------------------------- 3924 3925 private transient DigitList digitList = new DigitList(); 3926 3927 /** 3928 * The symbol used as a prefix when formatting positive numbers, e.g. "+". 3929 * 3930 * @serial 3931 * @see #getPositivePrefix 3932 */ 3933 private String positivePrefix = ""; 3934 3935 /** 3936 * The symbol used as a suffix when formatting positive numbers. 3937 * This is often an empty string. 3938 * 3939 * @serial 3940 * @see #getPositiveSuffix 3941 */ 3942 private String positiveSuffix = ""; 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 4174 * this class. 4175 * 4176 * Any {@code DecimalFormat} instance has a {@code fastPathData} 4177 * reference field that is null unless both the properties of the instance 4178 * are such that the instance is in the "fast-path" state, and a format call 4179 * has been done at least once while in this state. 4180 * 4181 * Almost all fields are related to the "fast-path" state only and don't 4182 * change until one of the instance properties is changed. 4183 * 4184 * {@code firstUsedIndex} and {@code lastFreeIndex} are the only 4185 * two fields that are used and modified while inside a call to 4186 * {@code fastDoubleFormat}. 4187 * 4188 */ 4189 private static class FastPathData { 4190 // --- Temporary fields used in fast-path, shared by several methods. 4191 4192 /** The first unused index at the end of the formatted result. */ 4193 int lastFreeIndex; 4194 4195 /** The first used index at the beginning of the formatted result */ 4196 int firstUsedIndex; 4197 4198 // --- State fields related to fast-path status. Changes due to a 4199 // property change only. Set by checkAndSetFastPathStatus() only. 4200 4201 /** Difference between locale zero and default zero representation. */ 4202 int zeroDelta; 4203 4204 /** Locale char for grouping separator. */ 4205 char groupingChar; 4206 4207 /** Fixed index position of last integral digit of formatted result */ 4208 int integralLastIndex; 4209 4210 /** Fixed index position of first fractional digit of formatted result */ 4211 int fractionalFirstIndex; 4212 4213 /** Fractional constants depending on decimal|currency state */ 4214 double fractionalScaleFactor; 4215 int fractionalMaxIntBound; 4216 4217 4218 /** The char array buffer that will contain the formatted result */ 4219 char[] fastPathContainer; 4220 4221 /** Suffixes recorded as char array for efficiency. */ 4222 char[] charsPositivePrefix; 4223 char[] charsNegativePrefix; 4224 char[] charsPositiveSuffix; 4225 char[] charsNegativeSuffix; 4226 boolean positiveAffixesRequired = true; 4227 boolean negativeAffixesRequired = true; 4228 } 4229 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 { 4283 static final char[] DigitOnes1000 = new char[1000]; 4284 static final char[] DigitTens1000 = new char[1000]; 4285 static final char[] DigitHundreds1000 = new char[1000]; 4286 4287 // initialize on demand holder class idiom for arrays of digits 4288 static { 4289 int tenIndex = 0; 4290 int hundredIndex = 0; 4291 char digitOne = '0'; 4292 char digitTen = '0'; 4293 char digitHundred = '0'; 4294 for (int i = 0; i < 1000; i++ ) { 4295 4296 DigitOnes1000[i] = digitOne; 4297 if (digitOne == '9') 4298 digitOne = '0'; 4299 else 4300 digitOne++; 4301 4302 DigitTens1000[i] = digitTen; 4303 if (i == (tenIndex + 9)) { 4304 tenIndex += 10; 4305 if (digitTen == '9') 4306 digitTen = '0'; 4307 else 4308 digitTen++; 4309 } 4310 4311 DigitHundreds1000[i] = digitHundred; 4312 if (i == (hundredIndex + 99)) { 4313 digitHundred++; 4314 hundredIndex += 100; 4315 } 4316 } 4317 } 4318 } 4319 // ------ Fast-Path for double Constants end ------ 4320 4321 // Constants for characters used in programmatic (unlocalized) patterns. 4322 private static final char PATTERN_ZERO_DIGIT = '0'; 4323 private static final char PATTERN_GROUPING_SEPARATOR = ','; 4324 private static final char PATTERN_DECIMAL_SEPARATOR = '.'; 4325 private static final char PATTERN_PER_MILLE = '\u2030'; 4326 private static final char PATTERN_PERCENT = '%'; 4327 private static final char PATTERN_DIGIT = '#'; 4328 private static final char PATTERN_SEPARATOR = ';'; 4329 private static final String PATTERN_EXPONENT = "E"; 4330 private static final char PATTERN_MINUS = '-'; 4331 4332 /** 4333 * The CURRENCY_SIGN is the standard Unicode symbol for currency. It 4334 * is used in patterns and substituted with either the currency symbol, 4335 * or if it is doubled, with the international currency symbol. If the 4336 * CURRENCY_SIGN is seen in a pattern, then the decimal separator is 4337 * replaced with the monetary decimal separator. 4338 * 4339 * The CURRENCY_SIGN is not localized. 4340 */ 4341 private static final char CURRENCY_SIGN = '\u00A4'; 4342 4343 private static final char QUOTE = '\''; 4344 4345 private static FieldPosition[] EmptyFieldPositionArray = new FieldPosition[0]; 4346 4347 // Upper limit on integer and fraction digits for a Java double 4348 static final int DOUBLE_INTEGER_DIGITS = 309; 4349 static final int DOUBLE_FRACTION_DIGITS = 340; 4350 4351 // Upper limit on integer and fraction digits for BigDecimal and BigInteger 4352 static final int MAXIMUM_INTEGER_DIGITS = Integer.MAX_VALUE; 4353 static final int MAXIMUM_FRACTION_DIGITS = Integer.MAX_VALUE; 4354 4355 // Proclaim JDK 1.1 serial compatibility. 4356 static final long serialVersionUID = 864413376551465018L; 4357 }