1 /* 2 * Copyright (c) 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 package java.text; 26 27 import java.io.IOException; 28 import java.io.InvalidObjectException; 29 import java.io.ObjectInputStream; 30 import java.math.BigDecimal; 31 import java.math.BigInteger; 32 import java.math.RoundingMode; 33 import java.util.ArrayList; 34 import java.util.Arrays; 35 import java.util.List; 36 import java.util.Locale; 37 import java.util.Objects; 38 import java.util.concurrent.atomic.AtomicInteger; 39 import java.util.concurrent.atomic.AtomicLong; 40 41 42 /** 43 * <p> 44 * {@code CompactNumberFormat} is a concrete subclass of {@code NumberFormat} 45 * that formats a decimal number in its compact form. 46 * 47 * The compact number formatting is designed for the environment where the space 48 * is limited, and the formatted string can be displayed in that limited space. 49 * It is defined by LDML's specification for 50 * <a href = "http://unicode.org/reports/tr35/tr35-numbers.html#Compact_Number_Formats"> 51 * Compact Number Formats</a>. A compact number formatting refers 52 * to the representation of a number in a shorter form, based on the patterns 53 * provided for a given locale. 54 * 55 * <p> 56 * For example: 57 * <br>In the {@link java.util.Locale#US US locale}, {@code 1000} can be formatted 58 * as {@code "1K"}, and {@code 1000000} as {@code "1M"}, depending upon the 59 * <a href = "#compact_number_style" >style</a> used. 60 * <br>In the {@code "hi_IN"} locale, {@code 1000} can be formatted as 61 * "1 \u0939\u091C\u093C\u093E\u0930", and {@code 50000000} as "5 \u0915.", 62 * depending upon the <a href = "#compact_number_style" >style</a> used. 63 * 64 * <p> 65 * To obtain a {@code CompactNumberFormat} for a locale, use one 66 * of the factory methods given by {@code NumberFormat} for compact number 67 * formatting. For example, 68 * {@link NumberFormat#getCompactNumberInstance(Locale, Style)}. 69 * 70 * <blockquote><pre> 71 * NumberFormat fmt = NumberFormat.getCompactNumberInstance( 72 * new Locale("hi", "IN"), NumberFormat.Style.SHORT); 73 * String result = fmt.format(1000); 74 * </pre></blockquote> 75 * 76 * <h3><a id="compact_number_style">Style</a></h3> 77 * <p> 78 * A number can be formatted in the compact forms with two different 79 * styles, {@link NumberFormat.Style#SHORT SHORT} 80 * and {@link NumberFormat.Style#LONG LONG}. Use 81 * {@link NumberFormat#getCompactNumberInstance(Locale, Style)} for formatting and 82 * parsing a number in {@link NumberFormat.Style#SHORT SHORT} or 83 * {@link NumberFormat.Style#LONG LONG} compact form, 84 * where the given {@code Style} parameter requests the desired 85 * format. A {@link NumberFormat.Style#SHORT SHORT} style 86 * compact number instance in the {@link java.util.Locale#US US locale} formats 87 * {@code 10000} as {@code "10K"}. However, a 88 * {@link NumberFormat.Style#LONG LONG} style instance in same locale 89 * formats {@code 10000} as {@code "10 thousand"}. 90 * 91 * <h3><a id="compact_number_patterns">Compact Number Patterns</a></h3> 92 * <p> 93 * The compact number patterns are represented in a series of patterns where each 94 * pattern is used to format a range of numbers. An example of 95 * {@link NumberFormat.Style#SHORT SHORT} styled compact number patterns 96 * for the {@link java.util.Locale#US US locale} is {@code {"", "", "", "0K", 97 * "00K", "000K", "0M", "00M", "000M", "0B", "00B", "000B", "0T", "00T", "000T"}}, 98 * ranging from {@code 10}<sup>{@code 0}</sup> to {@code 10}<sup>{@code 14}</sup>. 99 * There can be any number of patterns and they are 100 * strictly index based starting from the range {@code 10}<sup>{@code 0}</sup>. 101 * For example, in the above patterns, pattern at index 3 102 * ({@code "0K"}) is used for formatting {@code number >= 1000 and number < 10000}, 103 * pattern at index 4 ({@code "00K"}) is used for formatting 104 * {@code number >= 10000 and number < 100000} and so on. In most of the locales, 105 * patterns with the range 106 * {@code 10}<sup>{@code 0}</sup>-{@code 10}<sup>{@code 2}</sup> are empty 107 * strings, which implicitly means a special pattern {@code "0"}. 108 * A special pattern {@code "0"} is used for any range which does not contain 109 * a compact pattern. This special pattern can appear explicitly for any specific 110 * range, or considered as a default pattern for an empty string. 111 * <p> 112 * A compact pattern has the following syntax: 113 * <blockquote><pre> 114 * <i>Pattern:</i> 115 * <i>PositivePattern</i> 116 * <i>PositivePattern</i> <i>[; NegativePattern]<sub>optional</sub></i> 117 * <i>PositivePattern:</i> 118 * <i>Prefix<sub>optional</sub></i> <i>MinimumInteger</i> <i>Suffix<sub>optional</sub></i> 119 * <i>NegativePattern:</i> 120 * <i>Prefix<sub>optional</sub></i> <i>MinimumInteger</i> <i>Suffix<sub>optional</sub></i> 121 * <i>Prefix:</i> 122 * Any Unicode characters except \uFFFE, \uFFFF, and 123 * <a href = "DecimalFormat.html#special_pattern_character">special characters</a> 124 * <i>Suffix:</i> 125 * Any Unicode characters except \uFFFE, \uFFFF, and 126 * <a href = "DecimalFormat.html#special_pattern_character">special characters</a> 127 * <i>MinimumInteger:</i> 128 * 0 129 * 0 <i>MinimumInteger</i> 130 * </pre></blockquote> 131 * 132 * A compact pattern contains a positive and negative subpattern 133 * separated by a subpattern boundary character {@code ';' (U+003B)}, 134 * for example, {@code "0K;-0K"}. Each subpattern has a prefix, 135 * minimum integer digits, and suffix. The negative subpattern 136 * is optional, if absent, then the positive subpattern prefixed with the 137 * minus sign ({@code '-' U+002D HYPHEN-MINUS}) is used as the negative 138 * subpattern. That is, {@code "0K"} alone is equivalent to {@code "0K;-0K"}. 139 * If there is an explicit negative subpattern, it serves only to specify 140 * the negative prefix and suffix. The number of minimum integer digits, 141 * and other characteristics are all the same as the positive pattern. 142 * That means that {@code "0K;-00K"} produces precisely the same behavior 143 * as {@code "0K;-0K"}. 144 * 145 * <p> 146 * Many characters in a compact pattern are taken literally, they are matched 147 * during parsing and output unchanged during formatting. 148 * <a href = "DecimalFormat.html#special_pattern_character">Special characters</a>, 149 * on the other hand, stand for other characters, strings, or classes of 150 * characters. They must be quoted, using single quote {@code ' (U+0027)} 151 * unless noted otherwise, if they are to appear in the prefix or suffix 152 * as literals. For example, 0\u0915'.'. 153 * 154 * <h3>Formatting</h3> 155 * The default formatting behavior returns a formatted string with no fractional 156 * digits, however users can use the {@link #setMinimumFractionDigits(int)} 157 * method to include the fractional part. 158 * The number {@code 1000.0} or {@code 1000} is formatted as {@code "1K"} 159 * not {@code "1.00K"} (in the {@link java.util.Locale#US US locale}). For this 160 * reason, the patterns provided for formatting contain only the minimum 161 * integer digits, prefix and/or suffix, but no fractional part. 162 * For example, patterns used are {@code {"", "", "", 0K, 00K, ...}}. If the pattern 163 * selected for formatting a number is {@code "0"} (special pattern), 164 * either explicit or defaulted, then the general number formatting provided by 165 * {@link java.text.DecimalFormat DecimalFormat} 166 * for the specified locale is used. 167 * 168 * <h3>Parsing</h3> 169 * The default parsing behavior does not allow a grouping separator until 170 * grouping used is set to {@code true} by using 171 * {@link #setGroupingUsed(boolean)}. The parsing of the fractional part 172 * depends on the {@link #isParseIntegerOnly()}. For example, if the 173 * parse integer only is set to true, then the fractional part is skipped. 174 * 175 * <h3>Rounding</h3> 176 * {@code CompactNumberFormat} provides rounding modes defined in 177 * {@link java.math.RoundingMode} for formatting. By default, it uses 178 * {@link java.math.RoundingMode#HALF_EVEN RoundingMode.HALF_EVEN}. 179 * 180 * @see CompactNumberFormat.Style 181 * @see NumberFormat 182 * @see DecimalFormat 183 * @since 12 184 */ 185 public final class CompactNumberFormat extends NumberFormat { 186 187 private static final long serialVersionUID = 7128367218649234678L; 188 189 /** 190 * The patterns for compact form of numbers for this 191 * {@code CompactNumberFormat}. A possible example is 192 * {@code {"", "", "", "0K", "00K", "000K", "0M", "00M", "000M", "0B", 193 * "00B", "000B", "0T", "00T", "000T"}} ranging from 194 * {@code 10}<sup>{@code 0}</sup>-{@code 10}<sup>{@code 14}</sup>, 195 * where each pattern is used to format a range of numbers. 196 * For example, {@code "0K"} is used for formatting 197 * {@code number >= 1000 and number < 10000}, {@code "00K"} is used for 198 * formatting {@code number >= 10000 and number < 100000} and so on. 199 * This field must not be {@code null}. 200 * 201 * @serial 202 */ 203 private String[] compactPatterns; 204 205 /** 206 * List of positive prefix patterns of this formatter's 207 * compact number patterns. 208 */ 209 private transient List<String> positivePrefixPatterns; 210 211 /** 212 * List of negative prefix patterns of this formatter's 213 * compact number patterns. 214 */ 215 private transient List<String> negativePrefixPatterns; 216 217 /** 218 * List of positive suffix patterns of this formatter's 219 * compact number patterns. 220 */ 221 private transient List<String> positiveSuffixPatterns; 222 223 /** 224 * List of negative suffix patterns of this formatter's 225 * compact number patterns. 226 */ 227 private transient List<String> negativeSuffixPatterns; 228 229 /** 230 * List of divisors of this formatter's compact number patterns. 231 * Divisor can be either Long or BigInteger (if the divisor value goes 232 * beyond long boundary) 233 */ 234 private transient List<Number> divisors; 235 236 /** 237 * The {@code DecimalFormatSymbols} object used by this format. 238 * It contains the symbols used to format numbers. For example, 239 * the grouping separator, decimal separator, and so on. 240 * This field must not be {@code null}. 241 * 242 * @serial 243 * @see DecimalFormatSymbols 244 */ 245 private DecimalFormatSymbols symbols; 246 247 /** 248 * The decimal pattern which is used for formatting the numbers 249 * matching special pattern "0". This field must not be {@code null}. 250 * 251 * @serial 252 * @see DecimalFormat 253 */ 254 private final String decimalPattern; 255 256 /** 257 * A {@code DecimalFormat} used by this format for getting corresponding 258 * general number formatting behavior for compact numbers. 259 * 260 */ 261 private transient DecimalFormat decimalFormat; 262 263 /** 264 * A {@code DecimalFormat} used by this format for getting general number 265 * formatting behavior for the numbers which can't be represented as compact 266 * numbers. For example, number matching the special pattern "0" are 267 * formatted through general number format pattern provided by 268 * {@link java.text.DecimalFormat DecimalFormat} 269 * for the specified locale. 270 * 271 */ 272 private transient DecimalFormat defaultDecimalFormat; 273 274 /** 275 * The number of digits between grouping separators in the integer portion 276 * of a compact number. For the grouping to work while formatting, this 277 * field needs to be greater than 0 with grouping used set as true. 278 * This field must not be negative. 279 * 280 * @serial 281 */ 282 private byte groupingSize = 0; 283 284 /** 285 * Returns whether the {@link #parse(String, ParsePosition)} 286 * method returns {@code BigDecimal}. 287 * 288 * @serial 289 */ 290 private boolean parseBigDecimal = false; 291 292 /** 293 * The {@code RoundingMode} used in this compact number format. 294 * This field must not be {@code null}. 295 * 296 * @serial 297 */ 298 private RoundingMode roundingMode = RoundingMode.HALF_EVEN; 299 300 /** 301 * Special pattern used for compact numbers 302 */ 303 private static final String SPECIAL_PATTERN = "0"; 304 305 /** 306 * Multiplier for compact pattern range. In 307 * the list compact patterns each compact pattern 308 * specify the range with the multiplication factor of 10 309 * of its previous compact pattern range. 310 * For example, 10^0, 10^1, 10^2, 10^3, 10^4... 311 * 312 */ 313 private static final int RANGE_MULTIPLIER = 10; 314 315 /** 316 * Creates a {@code CompactNumberFormat} using the given decimal pattern, 317 * decimal format symbols and compact patterns. 318 * To obtain the instance of {@code CompactNumberFormat} with the standard 319 * compact patterns for a {@code Locale} and {@code Style}, 320 * it is recommended to use the factory methods given by 321 * {@code NumberFormat} for compact number formatting. For example, 322 * {@link NumberFormat#getCompactNumberInstance(Locale, Style)}. 323 * 324 * @param decimalPattern a decimal pattern for general number formatting 325 * @param symbols the set of symbols to be used 326 * @param compactPatterns an array of 327 * <a href = "CompactNumberFormat.html#compact_number_patterns"> 328 * compact number patterns</a> 329 * @throws NullPointerException if any of the given arguments is 330 * {@code null} 331 * @throws IllegalArgumentException if the given {@code decimalPattern} or the 332 * {@code compactPatterns} array contains an invalid pattern 333 * or if a {@code null} appears in the array of compact 334 * patterns 335 * @see DecimalFormat#DecimalFormat(java.lang.String, DecimalFormatSymbols) 336 * @see DecimalFormatSymbols 337 */ 338 public CompactNumberFormat(String decimalPattern, 339 DecimalFormatSymbols symbols, String[] compactPatterns) { 340 341 Objects.requireNonNull(decimalPattern, "decimalPattern"); 342 Objects.requireNonNull(symbols, "symbols"); 343 Objects.requireNonNull(compactPatterns, "compactPatterns"); 344 345 this.symbols = symbols; 346 // Instantiating the DecimalFormat with "0" pattern; this acts just as a 347 // basic pattern; the properties (For example, prefix/suffix) 348 // are later computed based on the compact number formatting process. 349 decimalFormat = new DecimalFormat(SPECIAL_PATTERN, this.symbols); 350 351 // Initializing the super class state with the decimalFormat values 352 // to represent this CompactNumberFormat. 353 // For setting the digits counts, use overridden setXXX methods of this 354 // CompactNumberFormat, as it performs check with the max range allowed 355 // for compact number formatting 356 setMaximumIntegerDigits(decimalFormat.getMaximumIntegerDigits()); 357 setMinimumIntegerDigits(decimalFormat.getMinimumIntegerDigits()); 358 setMaximumFractionDigits(decimalFormat.getMaximumFractionDigits()); 359 setMinimumFractionDigits(decimalFormat.getMinimumFractionDigits()); 360 361 super.setGroupingUsed(decimalFormat.isGroupingUsed()); 362 super.setParseIntegerOnly(decimalFormat.isParseIntegerOnly()); 363 364 this.compactPatterns = compactPatterns; 365 366 // DecimalFormat used for formatting numbers with special pattern "0". 367 // Formatting is delegated to the DecimalFormat's number formatting 368 // with no fraction digits 369 this.decimalPattern = decimalPattern; 370 defaultDecimalFormat = new DecimalFormat(this.decimalPattern, 371 this.symbols); 372 defaultDecimalFormat.setMaximumFractionDigits(0); 373 // Process compact patterns to extract the prefixes, suffixes and 374 // divisors 375 processCompactPatterns(); 376 } 377 378 /** 379 * Formats a number to produce a string representing its compact form. 380 * The number can be of any subclass of {@link java.lang.Number}. 381 * @param number the number to format 382 * @param toAppendTo the {@code StringBuffer} to which the formatted 383 * text is to be appended 384 * @param fieldPosition keeps track on the position of the field within 385 * the returned string. For example, for formatting 386 * a number {@code 123456789} in the 387 * {@link java.util.Locale#US US locale}, 388 * if the given {@code fieldPosition} is 389 * {@link NumberFormat#INTEGER_FIELD}, the begin 390 * index and end index of {@code fieldPosition} 391 * will be set to 0 and 3, respectively for the 392 * output string {@code 123M}. Similarly, positions 393 * of the prefix and the suffix fields can be 394 * obtained using {@link NumberFormat.Field#PREFIX} 395 * and {@link NumberFormat.Field#SUFFIX} respectively. 396 * @return the {@code StringBuffer} passed in as {@code toAppendTo} 397 * @throws IllegalArgumentException if {@code number} is 398 * {@code null} or not an instance of {@code Number} 399 * @throws NullPointerException if {@code toAppendTo} or 400 * {@code fieldPosition} is {@code null} 401 * @throws ArithmeticException if rounding is needed with rounding 402 * mode being set to {@code RoundingMode.UNNECESSARY} 403 * @see FieldPosition 404 */ 405 @Override 406 public final StringBuffer format(Object number, 407 StringBuffer toAppendTo, 408 FieldPosition fieldPosition) { 409 if (number instanceof Long || number instanceof Integer 410 || number instanceof Short || number instanceof Byte 411 || number instanceof AtomicInteger 412 || number instanceof AtomicLong 413 || (number instanceof BigInteger 414 && ((BigInteger) number).bitLength() < 64)) { 415 return format(((Number) number).longValue(), toAppendTo, 416 fieldPosition); 417 } else if (number instanceof BigDecimal) { 418 return format((BigDecimal) number, toAppendTo, fieldPosition); 419 } else if (number instanceof BigInteger) { 420 return format((BigInteger) number, toAppendTo, fieldPosition); 421 } else if (number instanceof Number) { 422 return format(((Number) number).doubleValue(), toAppendTo, fieldPosition); 423 } else { 424 throw new IllegalArgumentException("Cannot format " 425 + number.getClass().getName() + " as a number"); 426 } 427 } 428 429 /** 430 * Formats a double to produce a string representing its compact form. 431 * @param number the double number to format 432 * @param result where the text is to be appended 433 * @param fieldPosition keeps track on the position of the field within 434 * the returned string. For example, to format 435 * a number {@code 1234567.89} in the 436 * {@link java.util.Locale#US US locale} 437 * if the given {@code fieldPosition} is 438 * {@link NumberFormat#INTEGER_FIELD}, the begin 439 * index and end index of {@code fieldPosition} 440 * will be set to 0 and 1, respectively for the 441 * output string {@code 1M}. Similarly, positions 442 * of the prefix and the suffix fields can be 443 * obtained using {@link NumberFormat.Field#PREFIX} 444 * and {@link NumberFormat.Field#SUFFIX} respectively. 445 * @return the {@code StringBuffer} passed in as {@code result} 446 * @throws NullPointerException if {@code result} or 447 * {@code fieldPosition} is {@code null} 448 * @throws ArithmeticException if rounding is needed with rounding 449 * mode being set to {@code RoundingMode.UNNECESSARY} 450 * @see FieldPosition 451 */ 452 @Override 453 public StringBuffer format(double number, StringBuffer result, 454 FieldPosition fieldPosition) { 455 456 fieldPosition.setBeginIndex(0); 457 fieldPosition.setEndIndex(0); 458 return format(number, result, fieldPosition.getFieldDelegate()); 459 } 460 461 private StringBuffer format(double number, StringBuffer result, 462 FieldDelegate delegate) { 463 464 boolean nanOrInfinity = decimalFormat.handleNaN(number, result, delegate); 465 if (nanOrInfinity) { 466 return result; 467 } 468 469 boolean isNegative = ((number < 0.0) 470 || (number == 0.0 && 1 / number < 0.0)); 471 472 nanOrInfinity = decimalFormat.handleInfinity(number, result, delegate, isNegative); 473 if (nanOrInfinity) { 474 return result; 475 } 476 477 // Round the double value with min fraction digits, the integer 478 // part of the rounded value is used for matching the compact 479 // number pattern 480 // For example, if roundingMode is HALF_UP with min fraction 481 // digits = 0, the number 999.6 should round up 482 // to 1000 and outputs 1K/thousand in "en_US" locale 483 DigitList dList = new DigitList(); 484 dList.setRoundingMode(getRoundingMode()); 485 number = isNegative ? -number : number; 486 dList.set(isNegative, number, getMinimumFractionDigits()); 487 488 double roundedNumber = dList.getDouble(); 489 int compactDataIndex = selectCompactPattern((long) roundedNumber); 490 if (compactDataIndex != -1) { 491 String prefix = isNegative ? negativePrefixPatterns.get(compactDataIndex) 492 : positivePrefixPatterns.get(compactDataIndex); 493 String suffix = isNegative ? negativeSuffixPatterns.get(compactDataIndex) 494 : positiveSuffixPatterns.get(compactDataIndex); 495 496 if (!prefix.isEmpty() || !suffix.isEmpty()) { 497 appendPrefix(result, prefix, delegate); 498 long divisor = (Long) divisors.get(compactDataIndex); 499 roundedNumber = roundedNumber / divisor; 500 decimalFormat.setDigitList(roundedNumber, isNegative, getMaximumFractionDigits()); 501 decimalFormat.subformatNumber(result, delegate, isNegative, 502 false, getMaximumIntegerDigits(), getMinimumIntegerDigits(), 503 getMaximumFractionDigits(), getMinimumFractionDigits()); 504 appendSuffix(result, suffix, delegate); 505 } else { 506 defaultDecimalFormat.doubleSubformat(number, result, delegate, isNegative); 507 } 508 } else { 509 defaultDecimalFormat.doubleSubformat(number, result, delegate, isNegative); 510 } 511 return result; 512 } 513 514 /** 515 * Formats a long to produce a string representing its compact form. 516 * @param number the long number to format 517 * @param result where the text is to be appended 518 * @param fieldPosition keeps track on the position of the field within 519 * the returned string. For example, to format 520 * a number {@code 123456789} in the 521 * {@link java.util.Locale#US US locale}, 522 * if the given {@code fieldPosition} is 523 * {@link NumberFormat#INTEGER_FIELD}, the begin 524 * index and end index of {@code fieldPosition} 525 * will be set to 0 and 3, respectively for the 526 * output string {@code 123M}. Similarly, positions 527 * of the prefix and the suffix fields can be 528 * obtained using {@link NumberFormat.Field#PREFIX} 529 * and {@link NumberFormat.Field#SUFFIX} respectively. 530 * @return the {@code StringBuffer} passed in as {@code result} 531 * @throws NullPointerException if {@code result} or 532 * {@code fieldPosition} is {@code null} 533 * @throws ArithmeticException if rounding is needed with rounding 534 * mode being set to {@code RoundingMode.UNNECESSARY} 535 * @see FieldPosition 536 */ 537 @Override 538 public StringBuffer format(long number, StringBuffer result, 539 FieldPosition fieldPosition) { 540 541 fieldPosition.setBeginIndex(0); 542 fieldPosition.setEndIndex(0); 543 return format(number, result, fieldPosition.getFieldDelegate()); 544 } 545 546 private StringBuffer format(long number, StringBuffer result, FieldDelegate delegate) { 547 boolean isNegative = (number < 0); 548 if (isNegative) { 549 number = -number; 550 } 551 552 if (number < 0) { // LONG_MIN 553 BigInteger bigIntegerValue = BigInteger.valueOf(number); 554 return format(bigIntegerValue, result, delegate, true); 555 } 556 557 int compactDataIndex = selectCompactPattern(number); 558 if (compactDataIndex != -1) { 559 String prefix = isNegative ? negativePrefixPatterns.get(compactDataIndex) 560 : positivePrefixPatterns.get(compactDataIndex); 561 String suffix = isNegative ? negativeSuffixPatterns.get(compactDataIndex) 562 : positiveSuffixPatterns.get(compactDataIndex); 563 if (!prefix.isEmpty() || !suffix.isEmpty()) { 564 appendPrefix(result, prefix, delegate); 565 long divisor = (Long) divisors.get(compactDataIndex); 566 if ((number % divisor == 0)) { 567 number = number / divisor; 568 decimalFormat.setDigitList(number, isNegative, 0); 569 decimalFormat.subformatNumber(result, delegate, 570 isNegative, true, getMaximumIntegerDigits(), 571 getMinimumIntegerDigits(), getMaximumFractionDigits(), 572 getMinimumFractionDigits()); 573 } else { 574 // To avoid truncation of fractional part store 575 // the value in double and follow double path instead of 576 // long path 577 double dNumber = (double) number / divisor; 578 decimalFormat.setDigitList(dNumber, isNegative, getMaximumFractionDigits()); 579 decimalFormat.subformatNumber(result, delegate, 580 isNegative, false, getMaximumIntegerDigits(), 581 getMinimumIntegerDigits(), getMaximumFractionDigits(), 582 getMinimumFractionDigits()); 583 } 584 appendSuffix(result, suffix, delegate); 585 } else { 586 number = isNegative ? -number : number; 587 defaultDecimalFormat.format(number, result, delegate); 588 } 589 } else { 590 number = isNegative ? -number : number; 591 defaultDecimalFormat.format(number, result, delegate); 592 } 593 return result; 594 } 595 596 /** 597 * Formats a BigDecimal to produce a string representing its compact form. 598 * @param number the BigDecimal number to format 599 * @param result where the text is to be appended 600 * @param fieldPosition keeps track on the position of the field within 601 * the returned string. For example, to format 602 * a number {@code 1234567.89} in the 603 * {@link java.util.Locale#US US locale}, 604 * if the given {@code fieldPosition} is 605 * {@link NumberFormat#INTEGER_FIELD}, the begin 606 * index and end index of {@code fieldPosition} 607 * will be set to 0 and 1, respectively for the 608 * output string {@code 1M}. Similarly, positions 609 * of the prefix and the suffix fields can be 610 * obtained using {@link NumberFormat.Field#PREFIX} 611 * and {@link NumberFormat.Field#SUFFIX} respectively. 612 * @return the {@code StringBuffer} passed in as {@code result} 613 * @throws ArithmeticException if rounding is needed with rounding 614 * mode being set to {@code RoundingMode.UNNECESSARY} 615 * @throws NullPointerException if any of the given parameter 616 * is {@code null} 617 * @see FieldPosition 618 */ 619 private StringBuffer format(BigDecimal number, StringBuffer result, 620 FieldPosition fieldPosition) { 621 622 Objects.requireNonNull(number); 623 fieldPosition.setBeginIndex(0); 624 fieldPosition.setEndIndex(0); 625 return format(number, result, fieldPosition.getFieldDelegate()); 626 } 627 628 private StringBuffer format(BigDecimal number, StringBuffer result, 629 FieldDelegate delegate) { 630 631 boolean isNegative = number.signum() == -1; 632 if (isNegative) { 633 number = number.negate(); 634 } 635 636 // Round the value with min fraction digits, the integer 637 // part of the rounded value is used for matching the compact 638 // number pattern 639 // For example, If roundingMode is HALF_UP with min fraction digits = 0, 640 // the number 999.6 should round up 641 // to 1000 and outputs 1K/thousand in "en_US" locale 642 number = number.setScale(getMinimumFractionDigits(), getRoundingMode()); 643 644 int compactDataIndex; 645 if (number.toBigInteger().bitLength() < 64) { 646 compactDataIndex = selectCompactPattern(number.toBigInteger().longValue()); 647 } else { 648 compactDataIndex = selectCompactPattern(number.toBigInteger()); 649 } 650 651 if (compactDataIndex != -1) { 652 String prefix = isNegative ? negativePrefixPatterns.get(compactDataIndex) 653 : positivePrefixPatterns.get(compactDataIndex); 654 String suffix = isNegative ? negativeSuffixPatterns.get(compactDataIndex) 655 : positiveSuffixPatterns.get(compactDataIndex); 656 if (!prefix.isEmpty() || !suffix.isEmpty()) { 657 appendPrefix(result, prefix, delegate); 658 Number divisor = divisors.get(compactDataIndex); 659 number = number.divide(new BigDecimal(divisor.toString()), getRoundingMode()); 660 decimalFormat.setDigitList(number, isNegative, getMaximumFractionDigits()); 661 decimalFormat.subformatNumber(result, delegate, isNegative, 662 false, getMaximumIntegerDigits(), getMinimumIntegerDigits(), 663 getMaximumFractionDigits(), getMinimumFractionDigits()); 664 appendSuffix(result, suffix, delegate); 665 } else { 666 number = isNegative ? number.negate() : number; 667 defaultDecimalFormat.format(number, result, delegate); 668 } 669 } else { 670 number = isNegative ? number.negate() : number; 671 defaultDecimalFormat.format(number, result, delegate); 672 } 673 return result; 674 } 675 676 /** 677 * Formats a BigInteger to produce a string representing its compact form. 678 * @param number the BigInteger number to format 679 * @param result where the text is to be appended 680 * @param fieldPosition keeps track on the position of the field within 681 * the returned string. For example, to format 682 * a number {@code 123456789} in the 683 * {@link java.util.Locale#US US locale}, 684 * if the given {@code fieldPosition} is 685 * {@link NumberFormat#INTEGER_FIELD}, the begin index 686 * and end index of {@code fieldPosition} will be set 687 * to 0 and 3, respectively for the output string 688 * {@code 123M}. Similarly, positions of the 689 * prefix and the suffix fields can be obtained 690 * using {@link NumberFormat.Field#PREFIX} and 691 * {@link NumberFormat.Field#SUFFIX} respectively. 692 * @return the {@code StringBuffer} passed in as {@code result} 693 * @throws ArithmeticException if rounding is needed with rounding 694 * mode being set to {@code RoundingMode.UNNECESSARY} 695 * @throws NullPointerException if any of the given parameter 696 * is {@code null} 697 * @see FieldPosition 698 */ 699 private StringBuffer format(BigInteger number, StringBuffer result, 700 FieldPosition fieldPosition) { 701 702 Objects.requireNonNull(number); 703 fieldPosition.setBeginIndex(0); 704 fieldPosition.setEndIndex(0); 705 return format(number, result, fieldPosition.getFieldDelegate(), false); 706 } 707 708 private StringBuffer format(BigInteger number, StringBuffer result, 709 FieldDelegate delegate, boolean formatLong) { 710 711 boolean isNegative = number.signum() == -1; 712 if (isNegative) { 713 number = number.negate(); 714 } 715 716 int compactDataIndex = selectCompactPattern(number); 717 if (compactDataIndex != -1) { 718 String prefix = isNegative ? negativePrefixPatterns.get(compactDataIndex) 719 : positivePrefixPatterns.get(compactDataIndex); 720 String suffix = isNegative ? negativeSuffixPatterns.get(compactDataIndex) 721 : positiveSuffixPatterns.get(compactDataIndex); 722 if (!prefix.isEmpty() || !suffix.isEmpty()) { 723 appendPrefix(result, prefix, delegate); 724 Number divisor = divisors.get(compactDataIndex); 725 if (number.mod(new BigInteger(divisor.toString())) 726 .compareTo(BigInteger.ZERO) == 0) { 727 number = number.divide(new BigInteger(divisor.toString())); 728 729 decimalFormat.setDigitList(number, isNegative, 0); 730 decimalFormat.subformatNumber(result, delegate, 731 isNegative, true, getMaximumIntegerDigits(), 732 getMinimumIntegerDigits(), getMaximumFractionDigits(), 733 getMinimumFractionDigits()); 734 } else { 735 // To avoid truncation of fractional part store the value in 736 // BigDecimal and follow BigDecimal path instead of 737 // BigInteger path 738 BigDecimal nDecimal = new BigDecimal(number) 739 .divide(new BigDecimal(divisor.toString()), getRoundingMode()); 740 decimalFormat.setDigitList(nDecimal, isNegative, getMaximumFractionDigits()); 741 decimalFormat.subformatNumber(result, delegate, 742 isNegative, false, getMaximumIntegerDigits(), 743 getMinimumIntegerDigits(), getMaximumFractionDigits(), 744 getMinimumFractionDigits()); 745 } 746 appendSuffix(result, suffix, delegate); 747 } else { 748 number = isNegative ? number.negate() : number; 749 defaultDecimalFormat.format(number, result, delegate, formatLong); 750 } 751 } else { 752 number = isNegative ? number.negate() : number; 753 defaultDecimalFormat.format(number, result, delegate, formatLong); 754 } 755 return result; 756 } 757 758 /** 759 * Appends the {@code prefix} to the {@code result} and also set the 760 * {@code NumberFormat.Field.SIGN} and {@code NumberFormat.Field.PREFIX} 761 * field positions. 762 * @param result the resulting string, where the pefix is to be appended 763 * @param prefix prefix to append 764 * @param delegate notified of the locations of 765 * {@code NumberFormat.Field.SIGN} and 766 * {@code NumberFormat.Field.PREFIX} fields 767 */ 768 private void appendPrefix(StringBuffer result, String prefix, 769 FieldDelegate delegate) { 770 append(result, expandAffix(prefix), delegate, 771 getFieldPositions(prefix, NumberFormat.Field.PREFIX)); 772 } 773 774 /** 775 * Appends {@code suffix} to the {@code result} and also set the 776 * {@code NumberFormat.Field.SIGN} and {@code NumberFormat.Field.SUFFIX} 777 * field positions. 778 * @param result the resulting string, where the suffix is to be appended 779 * @param suffix suffix to append 780 * @param delegate notified of the locations of 781 * {@code NumberFormat.Field.SIGN} and 782 * {@code NumberFormat.Field.SUFFIX} fields 783 */ 784 private void appendSuffix(StringBuffer result, String suffix, 785 FieldDelegate delegate) { 786 append(result, expandAffix(suffix), delegate, 787 getFieldPositions(suffix, NumberFormat.Field.SUFFIX)); 788 } 789 790 /** 791 * Appends the {@code string} to the {@code result}. 792 * {@code delegate} is notified of SIGN, PREFIX and/or SUFFIX 793 * field positions. 794 * @param result the resulting string, where the text is to be appended 795 * @param string the text to append 796 * @param delegate notified of the locations of sub fields 797 * @param positions a list of {@code FieldPostion} in the given 798 * string 799 */ 800 private void append(StringBuffer result, String string, 801 FieldDelegate delegate, List<FieldPosition> positions) { 802 if (!string.isEmpty()) { 803 int start = result.length(); 804 result.append(string); 805 for (int counter = 0; counter < positions.size(); counter++) { 806 FieldPosition fp = positions.get(counter); 807 Format.Field attribute = fp.getFieldAttribute(); 808 delegate.formatted(attribute, attribute, 809 start + fp.getBeginIndex(), 810 start + fp.getEndIndex(), result); 811 } 812 } 813 } 814 815 /** 816 * Expands an affix {@code pattern} into a string of literals. 817 * All characters in the pattern are literals unless prefixed by QUOTE. 818 * The character prefixed by QUOTE is replaced with its respective 819 * localized literal. 820 * @param pattern a compact number pattern affix 821 * @return an expanded affix 822 */ 823 private String expandAffix(String pattern) { 824 // Return if no quoted character exists 825 if (pattern.indexOf(QUOTE) < 0) { 826 return pattern; 827 } 828 StringBuilder sb = new StringBuilder(); 829 for (int index = 0; index < pattern.length();) { 830 char ch = pattern.charAt(index++); 831 if (ch == QUOTE) { 832 ch = pattern.charAt(index++); 833 if (ch == MINUS_SIGN) { 834 ch = symbols.getMinusSign(); 835 } 836 } 837 sb.append(ch); 838 } 839 return sb.toString(); 840 } 841 842 /** 843 * Returns a list of {@code FieldPostion} in the given {@code pattern}. 844 * @param pattern the pattern to be parsed for {@code FieldPosition} 845 * @param field whether a PREFIX or SUFFIX field 846 * @return a list of {@code FieldPostion} 847 */ 848 private List<FieldPosition> getFieldPositions(String pattern, Field field) { 849 List<FieldPosition> positions = new ArrayList<>(); 850 StringBuilder affix = new StringBuilder(); 851 int stringIndex = 0; 852 for (int index = 0; index < pattern.length();) { 853 char ch = pattern.charAt(index++); 854 if (ch == QUOTE) { 855 ch = pattern.charAt(index++); 856 if (ch == MINUS_SIGN) { 857 ch = symbols.getMinusSign(); 858 FieldPosition fp = new FieldPosition(NumberFormat.Field.SIGN); 859 fp.setBeginIndex(stringIndex); 860 fp.setEndIndex(stringIndex + 1); 861 positions.add(fp); 862 } 863 } 864 stringIndex++; 865 affix.append(ch); 866 } 867 if (affix.length() != 0) { 868 FieldPosition fp = new FieldPosition(field); 869 fp.setBeginIndex(0); 870 fp.setEndIndex(affix.length()); 871 positions.add(fp); 872 } 873 return positions; 874 } 875 876 /** 877 * Select the index of the matched compact number pattern for 878 * the given {@code long} {@code number}. 879 * 880 * @param number number to be formatted 881 * @return index of matched compact pattern; 882 * -1 if no compact patterns specified 883 */ 884 private int selectCompactPattern(long number) { 885 886 if (compactPatterns.length == 0) { 887 return -1; 888 } 889 890 // Minimum index can be "0", max index can be "size - 1" 891 int dataIndex = number <= 1 ? 0 : (int) Math.log10(number); 892 dataIndex = Math.min(dataIndex, compactPatterns.length - 1); 893 return dataIndex; 894 } 895 896 /** 897 * Select the index of the matched compact number 898 * pattern for the given {@code BigInteger} {@code number}. 899 * 900 * @param number number to be formatted 901 * @return index of matched compact pattern; 902 * -1 if no compact patterns specified 903 */ 904 private int selectCompactPattern(BigInteger number) { 905 906 int matchedIndex = -1; 907 if (compactPatterns.length == 0) { 908 return matchedIndex; 909 } 910 911 BigInteger currentValue = BigInteger.ONE; 912 913 // For formatting a number, the greatest type less than 914 // or equal to number is used 915 for (int index = 0; index < compactPatterns.length; index++) { 916 if (number.compareTo(currentValue) > 0) { 917 // Input number is greater than current type; try matching with 918 // the next 919 matchedIndex = index; 920 currentValue = currentValue.multiply(BigInteger.valueOf(RANGE_MULTIPLIER)); 921 continue; 922 } 923 if (number.compareTo(currentValue) < 0) { 924 // Current type is greater than the input number; 925 // take the previous pattern 926 break; 927 } else { 928 // Equal 929 matchedIndex = index; 930 break; 931 } 932 } 933 return matchedIndex; 934 } 935 936 /** 937 * Formats an Object producing an {@code AttributedCharacterIterator}. 938 * The returned {@code AttributedCharacterIterator} can be used 939 * to build the resulting string, as well as to determine information 940 * about the resulting string. 941 * <p> 942 * Each attribute key of the {@code AttributedCharacterIterator} will 943 * be of type {@code NumberFormat.Field}, with the attribute value 944 * being the same as the attribute key. The prefix and the suffix 945 * parts of the returned iterator (if present) are represented by 946 * the attributes {@link NumberFormat.Field#PREFIX} and 947 * {@link NumberFormat.Field#SUFFIX} respectively. 948 * 949 * 950 * @throws NullPointerException if obj is null 951 * @throws IllegalArgumentException when the Format cannot format the 952 * given object 953 * @throws ArithmeticException if rounding is needed with rounding 954 * mode being set to {@code RoundingMode.UNNECESSARY} 955 * @param obj The object to format 956 * @return an {@code AttributedCharacterIterator} describing the 957 * formatted value 958 */ 959 @Override 960 public AttributedCharacterIterator formatToCharacterIterator(Object obj) { 961 CharacterIteratorFieldDelegate delegate 962 = new CharacterIteratorFieldDelegate(); 963 StringBuffer sb = new StringBuffer(); 964 965 if (obj instanceof Double || obj instanceof Float) { 966 format(((Number) obj).doubleValue(), sb, delegate); 967 } else if (obj instanceof Long || obj instanceof Integer 968 || obj instanceof Short || obj instanceof Byte 969 || obj instanceof AtomicInteger || obj instanceof AtomicLong) { 970 format(((Number) obj).longValue(), sb, delegate); 971 } else if (obj instanceof BigDecimal) { 972 format((BigDecimal) obj, sb, delegate); 973 } else if (obj instanceof BigInteger) { 974 format((BigInteger) obj, sb, delegate, false); 975 } else if (obj == null) { 976 throw new NullPointerException( 977 "formatToCharacterIterator must be passed non-null object"); 978 } else { 979 throw new IllegalArgumentException( 980 "Cannot format given Object as a Number"); 981 } 982 return delegate.getIterator(sb.toString()); 983 } 984 985 /** 986 * Computes the divisor using minimum integer digits and 987 * matched pattern index. 988 * @param minIntDigits string of 0s in compact pattern 989 * @param patternIndex index of matched compact pattern 990 * @return divisor value for the number matching the compact 991 * pattern at given {@code patternIndex} 992 */ 993 private Number computeDivisor(String minIntDigits, int patternIndex) { 994 int count = minIntDigits.length() - 1; 995 Number matchedValue; 996 // The divisor value can go above long range, if the compact patterns 997 // goes above index 18, divisor may need to be stored as BigInteger, 998 // since long can't store numbers >= 10^19, 999 if (patternIndex < 19) { 1000 matchedValue = (long) Math.pow(RANGE_MULTIPLIER, patternIndex); 1001 } else { 1002 matchedValue = BigInteger.valueOf(RANGE_MULTIPLIER).pow(patternIndex); 1003 } 1004 Number divisor = matchedValue; 1005 if (count != 0) { 1006 if (matchedValue instanceof BigInteger) { 1007 BigInteger bigValue = (BigInteger) matchedValue; 1008 if (bigValue.compareTo(BigInteger.valueOf((long) Math.pow(RANGE_MULTIPLIER, count))) < 0) { 1009 throw new IllegalArgumentException("Invalid Pattern" 1010 + " [" + compactPatterns[patternIndex] 1011 + "]: min integer digits specified exceeds the limit" 1012 + " for the index " + patternIndex); 1013 } 1014 divisor = bigValue.divide(BigInteger.valueOf((long) Math.pow(RANGE_MULTIPLIER, count))); 1015 } else { 1016 long longValue = (long) matchedValue; 1017 if (longValue < (long) Math.pow(RANGE_MULTIPLIER, count)) { 1018 throw new IllegalArgumentException("Invalid Pattern" 1019 + " [" + compactPatterns[patternIndex] 1020 + "]: min integer digits specified exceeds the limit" 1021 + " for the index " + patternIndex); 1022 } 1023 divisor = longValue / (long) Math.pow(RANGE_MULTIPLIER, count); 1024 } 1025 } 1026 return divisor; 1027 } 1028 1029 /** 1030 * Process the series of compact patterns to compute the 1031 * series of prefixes, suffixes and their respective divisor 1032 * value. 1033 * 1034 */ 1035 private void processCompactPatterns() { 1036 int size = compactPatterns.length; 1037 positivePrefixPatterns = new ArrayList<>(size); 1038 negativePrefixPatterns = new ArrayList<>(size); 1039 positiveSuffixPatterns = new ArrayList<>(size); 1040 negativeSuffixPatterns = new ArrayList<>(size); 1041 divisors = new ArrayList<>(size); 1042 1043 for (int index = 0; index < size; index++) { 1044 applyPattern(compactPatterns[index], index); 1045 } 1046 } 1047 1048 /** 1049 * Process a compact pattern at a specific {@code index} 1050 * @param pattern the compact pattern to be processed 1051 * @param index index in the array of compact patterns 1052 * 1053 */ 1054 private void applyPattern(String pattern, int index) { 1055 1056 int start = 0; 1057 boolean gotNegative = false; 1058 1059 String positivePrefix = ""; 1060 String positiveSuffix = ""; 1061 String negativePrefix = ""; 1062 String negativeSuffix = ""; 1063 String zeros = ""; 1064 for (int j = 1; j >= 0 && start < pattern.length(); --j) { 1065 1066 StringBuffer prefix = new StringBuffer(); 1067 StringBuffer suffix = new StringBuffer(); 1068 boolean inQuote = false; 1069 // The phase ranges from 0 to 2. Phase 0 is the prefix. Phase 1 is 1070 // the section of the pattern with digits. Phase 2 is the suffix. 1071 // The separation of the characters into phases is 1072 // strictly enforced; if phase 1 characters are to appear in the 1073 // suffix, for example, they must be quoted. 1074 int phase = 0; 1075 1076 // The affix is either the prefix or the suffix. 1077 StringBuffer affix = prefix; 1078 1079 for (int pos = start; pos < pattern.length(); ++pos) { 1080 char ch = pattern.charAt(pos); 1081 switch (phase) { 1082 case 0: 1083 case 2: 1084 // Process the prefix / suffix characters 1085 if (inQuote) { 1086 // A quote within quotes indicates either the closing 1087 // quote or two quotes, which is a quote literal. That 1088 // is, we have the second quote in 'do' or 'don''t'. 1089 if (ch == QUOTE) { 1090 if ((pos + 1) < pattern.length() 1091 && pattern.charAt(pos + 1) == QUOTE) { 1092 ++pos; 1093 affix.append("''"); // 'don''t' 1094 } else { 1095 inQuote = false; // 'do' 1096 } 1097 continue; 1098 } 1099 } else { 1100 // Process unquoted characters seen in prefix or suffix 1101 // phase. 1102 switch (ch) { 1103 case ZERO_DIGIT: 1104 phase = 1; 1105 --pos; // Reprocess this character 1106 continue; 1107 case QUOTE: 1108 // A quote outside quotes indicates either the 1109 // opening quote or two quotes, which is a quote 1110 // literal. That is, we have the first quote in 'do' 1111 // or o''clock. 1112 if ((pos + 1) < pattern.length() 1113 && pattern.charAt(pos + 1) == QUOTE) { 1114 ++pos; 1115 affix.append("''"); // o''clock 1116 } else { 1117 inQuote = true; // 'do' 1118 } 1119 continue; 1120 case SEPARATOR: 1121 // Don't allow separators before we see digit 1122 // characters of phase 1, and don't allow separators 1123 // in the second pattern (j == 0). 1124 if (phase == 0 || j == 0) { 1125 throw new IllegalArgumentException( 1126 "Unquoted special character '" 1127 + ch + "' in pattern \"" + pattern + "\""); 1128 } 1129 start = pos + 1; 1130 pos = pattern.length(); 1131 continue; 1132 case MINUS_SIGN: 1133 affix.append("'-"); 1134 continue; 1135 case DECIMAL_SEPARATOR: 1136 case GROUPING_SEPARATOR: 1137 case DIGIT: 1138 case PERCENT: 1139 case PER_MILLE: 1140 case CURRENCY_SIGN: 1141 throw new IllegalArgumentException( 1142 "Unquoted special character '" + ch 1143 + "' in pattern \"" + pattern + "\""); 1144 default: 1145 break; 1146 } 1147 } 1148 // Note that if we are within quotes, or if this is an 1149 // unquoted, non-special character, then we usually fall 1150 // through to here. 1151 affix.append(ch); 1152 break; 1153 1154 case 1: 1155 // The negative subpattern (j = 0) serves only to specify the 1156 // negative prefix and suffix, so all the phase 1 characters, 1157 // for example, digits, zeroDigit, groupingSeparator, 1158 // decimalSeparator, exponent are ignored 1159 if (j == 0) { 1160 while (pos < pattern.length()) { 1161 char negPatternChar = pattern.charAt(pos); 1162 if (negPatternChar == ZERO_DIGIT) { 1163 ++pos; 1164 } else { 1165 // Not a phase 1 character, consider it as 1166 // suffix and parse it in phase 2 1167 --pos; //process it again in outer loop 1168 phase = 2; 1169 affix = suffix; 1170 break; 1171 } 1172 } 1173 continue; 1174 } 1175 // Consider only '0' as valid pattern char which can appear 1176 // in number part, rest can be either suffix or prefix 1177 if (ch == ZERO_DIGIT) { 1178 zeros = zeros + "0"; 1179 } else { 1180 phase = 2; 1181 affix = suffix; 1182 --pos; 1183 } 1184 break; 1185 } 1186 } 1187 1188 if (inQuote) { 1189 throw new IllegalArgumentException("Invalid single quote" 1190 + " in pattern \"" + pattern + "\""); 1191 } 1192 1193 if (j == 1) { 1194 positivePrefix = prefix.toString(); 1195 positiveSuffix = suffix.toString(); 1196 negativePrefix = positivePrefix; 1197 negativeSuffix = positiveSuffix; 1198 } else { 1199 negativePrefix = prefix.toString(); 1200 negativeSuffix = suffix.toString(); 1201 gotNegative = true; 1202 } 1203 1204 // If there is no negative pattern, or if the negative pattern is 1205 // identical to the positive pattern, then prepend the minus sign to 1206 // the positive pattern to form the negative pattern. 1207 if (!gotNegative 1208 || (negativePrefix.equals(positivePrefix) 1209 && negativeSuffix.equals(positiveSuffix))) { 1210 negativeSuffix = positiveSuffix; 1211 negativePrefix = "'-" + positivePrefix; 1212 } 1213 } 1214 1215 // If no 0s are specified in a non empty pattern, it is invalid 1216 if (!pattern.isEmpty() && zeros.isEmpty()) { 1217 throw new IllegalArgumentException("Invalid pattern" 1218 + " [" + pattern + "]: all patterns must include digit" 1219 + " placement 0s"); 1220 } 1221 1222 // Only if positive affix exists; else put empty strings 1223 if (!positivePrefix.isEmpty() || !positiveSuffix.isEmpty()) { 1224 positivePrefixPatterns.add(positivePrefix); 1225 negativePrefixPatterns.add(negativePrefix); 1226 positiveSuffixPatterns.add(positiveSuffix); 1227 negativeSuffixPatterns.add(negativeSuffix); 1228 divisors.add(computeDivisor(zeros, index)); 1229 } else { 1230 positivePrefixPatterns.add(""); 1231 negativePrefixPatterns.add(""); 1232 positiveSuffixPatterns.add(""); 1233 negativeSuffixPatterns.add(""); 1234 divisors.add(1L); 1235 } 1236 } 1237 1238 private final transient DigitList digitList = new DigitList(); 1239 private static final int STATUS_INFINITE = 0; 1240 private static final int STATUS_POSITIVE = 1; 1241 private static final int STATUS_LENGTH = 2; 1242 1243 private static final char ZERO_DIGIT = '0'; 1244 private static final char DIGIT = '#'; 1245 private static final char DECIMAL_SEPARATOR = '.'; 1246 private static final char GROUPING_SEPARATOR = ','; 1247 private static final char MINUS_SIGN = '-'; 1248 private static final char PERCENT = '%'; 1249 private static final char PER_MILLE = '\u2030'; 1250 private static final char SEPARATOR = ';'; 1251 private static final char CURRENCY_SIGN = '\u00A4'; 1252 private static final char QUOTE = '\''; 1253 1254 // Expanded form of positive/negative prefix/suffix, 1255 // the expanded form contains special characters in 1256 // its localized form, which are used for matching 1257 // while parsing a string to number 1258 private transient List<String> positivePrefixes; 1259 private transient List<String> negativePrefixes; 1260 private transient List<String> positiveSuffixes; 1261 private transient List<String> negativeSuffixes; 1262 1263 private void expandAffixPatterns() { 1264 positivePrefixes = new ArrayList<>(compactPatterns.length); 1265 negativePrefixes = new ArrayList<>(compactPatterns.length); 1266 positiveSuffixes = new ArrayList<>(compactPatterns.length); 1267 negativeSuffixes = new ArrayList<>(compactPatterns.length); 1268 for (int index = 0; index < compactPatterns.length; index++) { 1269 positivePrefixes.add(expandAffix(positivePrefixPatterns.get(index))); 1270 negativePrefixes.add(expandAffix(negativePrefixPatterns.get(index))); 1271 positiveSuffixes.add(expandAffix(positiveSuffixPatterns.get(index))); 1272 negativeSuffixes.add(expandAffix(negativeSuffixPatterns.get(index))); 1273 } 1274 } 1275 1276 /** 1277 * Parses a compact number from a string to produce a {@code Number}. 1278 * <p> 1279 * The method attempts to parse text starting at the index given by 1280 * {@code pos}. 1281 * If parsing succeeds, then the index of {@code pos} is updated 1282 * to the index after the last character used (parsing does not necessarily 1283 * use all characters up to the end of the string), and the parsed 1284 * number is returned. The updated {@code pos} can be used to 1285 * indicate the starting point for the next call to this method. 1286 * If an error occurs, then the index of {@code pos} is not 1287 * changed, the error index of {@code pos} is set to the index of 1288 * the character where the error occurred, and {@code null} is returned. 1289 * <p> 1290 * The value is the numeric part in the given text multiplied 1291 * by the numeric equivalent of the affix attached 1292 * (For example, "K" = 1000 in {@link java.util.Locale#US US locale}). 1293 * The subclass returned depends on the value of 1294 * {@link #isParseBigDecimal}. 1295 * <ul> 1296 * <li>If {@link #isParseBigDecimal()} is false (the default), 1297 * most integer values are returned as {@code Long} 1298 * objects, no matter how they are written: {@code "17K"} and 1299 * {@code "17.000K"} both parse to {@code Long.valueOf(17000)}. 1300 * If the value cannot fit into {@code Long}, then the result is 1301 * returned as {@code Double}. This includes values with a 1302 * fractional part, infinite values, {@code NaN}, 1303 * and the value -0.0. 1304 * <p> 1305 * Callers may use the {@code Number} methods {@code doubleValue}, 1306 * {@code longValue}, etc., to obtain the type they want. 1307 * 1308 * <li>If {@link #isParseBigDecimal()} is true, values are returned 1309 * as {@code BigDecimal} objects. The special cases negative 1310 * and positive infinity and NaN are returned as {@code Double} 1311 * instances holding the values of the corresponding 1312 * {@code Double} constants. 1313 * </ul> 1314 * <p> 1315 * {@code CompactNumberFormat} parses all Unicode characters that represent 1316 * decimal digits, as defined by {@code Character.digit()}. In 1317 * addition, {@code CompactNumberFormat} also recognizes as digits the ten 1318 * consecutive characters starting with the localized zero digit defined in 1319 * the {@code DecimalFormatSymbols} object. 1320 * <p> 1321 * {@code CompactNumberFormat} parse does not allow parsing scientific 1322 * notations. For example, parsing a string {@code "1.05E4K"} in 1323 * {@link java.util.Locale#US US locale} breaks at character 'E' 1324 * and returns 1.05. 1325 * 1326 * @param text the string to be parsed 1327 * @param pos a {@code ParsePosition} object with index and error 1328 * index information as described above 1329 * @return the parsed value, or {@code null} if the parse fails 1330 * @exception NullPointerException if {@code text} or 1331 * {@code pos} is null 1332 * 1333 */ 1334 @Override 1335 public Number parse(String text, ParsePosition pos) { 1336 1337 Objects.requireNonNull(text); 1338 Objects.requireNonNull(pos); 1339 1340 // Lazily expanding the affix patterns, on the first parse 1341 // call on this instance 1342 // If not initialized, expand and load all affixes 1343 if (positivePrefixes == null) { 1344 expandAffixPatterns(); 1345 } 1346 1347 // The compact number multiplier for parsed string. 1348 // Its value is set on parsing prefix and suffix. For example, 1349 // in the {@link java.util.Locale#US US locale} parsing {@code "1K"} 1350 // sets its value to 1000, as K (thousand) is abbreviated form of 1000. 1351 Number cnfMultiplier = 1L; 1352 1353 // Special case NaN 1354 if (text.regionMatches(pos.index, symbols.getNaN(), 1355 0, symbols.getNaN().length())) { 1356 pos.index = pos.index + symbols.getNaN().length(); 1357 return Double.NaN; 1358 } 1359 1360 int position = pos.index; 1361 int oldStart = pos.index; 1362 boolean gotPositive = false; 1363 boolean gotNegative = false; 1364 int matchedPosIndex = -1; 1365 int matchedNegIndex = -1; 1366 String matchedPosPrefix = ""; 1367 String matchedNegPrefix = ""; 1368 String defaultPosPrefix = defaultDecimalFormat.getPositivePrefix(); 1369 String defaultNegPrefix = defaultDecimalFormat.getNegativePrefix(); 1370 // Prefix matching 1371 for (int compactIndex = 0; compactIndex < compactPatterns.length; compactIndex++) { 1372 String positivePrefix = positivePrefixes.get(compactIndex); 1373 String negativePrefix = negativePrefixes.get(compactIndex); 1374 1375 // Do not break if a match occur; there is a possibility that the 1376 // subsequent affixes may match the longer subsequence in the given 1377 // string. 1378 // For example, matching "Mdx 3" with "M", "Md" as prefix should 1379 // match with "Md" 1380 boolean match = matchAffix(text, position, positivePrefix, 1381 defaultPosPrefix, matchedPosPrefix); 1382 if (match) { 1383 matchedPosIndex = compactIndex; 1384 matchedPosPrefix = positivePrefix; 1385 gotPositive = true; 1386 } 1387 1388 match = matchAffix(text, position, negativePrefix, 1389 defaultNegPrefix, matchedNegPrefix); 1390 if (match) { 1391 matchedNegIndex = compactIndex; 1392 matchedNegPrefix = negativePrefix; 1393 gotNegative = true; 1394 } 1395 } 1396 1397 // Given text does not match the non empty valid compact prefixes 1398 // check with the default prefixes 1399 if (!gotPositive && !gotNegative) { 1400 if (text.regionMatches(pos.index, defaultPosPrefix, 0, 1401 defaultPosPrefix.length())) { 1402 // Matches the default positive prefix 1403 matchedPosPrefix = defaultPosPrefix; 1404 gotPositive = true; 1405 } 1406 if (text.regionMatches(pos.index, defaultNegPrefix, 0, 1407 defaultNegPrefix.length())) { 1408 // Matches the default negative prefix 1409 matchedNegPrefix = defaultNegPrefix; 1410 gotNegative = true; 1411 } 1412 } 1413 1414 // If both match, take the longest one 1415 if (gotPositive && gotNegative) { 1416 if (matchedPosPrefix.length() > matchedNegPrefix.length()) { 1417 gotNegative = false; 1418 } else if (matchedPosPrefix.length() < matchedNegPrefix.length()) { 1419 gotPositive = false; 1420 } 1421 } 1422 1423 // Update the position and take compact multiplier 1424 // only if it matches the compact prefix, not the default 1425 // prefix; else multiplier should be 1 1426 if (gotPositive) { 1427 position += matchedPosPrefix.length(); 1428 cnfMultiplier = matchedPosIndex != -1 1429 ? divisors.get(matchedPosIndex) : 1L; 1430 } else if (gotNegative) { 1431 position += matchedNegPrefix.length(); 1432 cnfMultiplier = matchedNegIndex != -1 1433 ? divisors.get(matchedNegIndex) : 1L; 1434 } 1435 1436 digitList.setRoundingMode(getRoundingMode()); 1437 boolean[] status = new boolean[STATUS_LENGTH]; 1438 1439 // Call DecimalFormat.subparseNumber() method to parse the 1440 // number part of the input text 1441 position = decimalFormat.subparseNumber(text, position, 1442 digitList, false, false, status); 1443 1444 if (position == -1) { 1445 // Unable to parse the number successfully 1446 pos.index = oldStart; 1447 pos.errorIndex = oldStart; 1448 return null; 1449 } 1450 1451 // If parse integer only is true and the parsing is broken at 1452 // decimal point, then pass/ignore all digits and move pointer 1453 // at the start of suffix, to process the suffix part 1454 if (isParseIntegerOnly() 1455 && text.charAt(position) == symbols.getDecimalSeparator()) { 1456 position++; // Pass decimal character 1457 for (; position < text.length(); ++position) { 1458 char ch = text.charAt(position); 1459 int digit = ch - symbols.getZeroDigit(); 1460 if (digit < 0 || digit > 9) { 1461 digit = Character.digit(ch, 10); 1462 // Parse all digit characters 1463 if (!(digit >= 0 && digit <= 9)) { 1464 break; 1465 } 1466 } 1467 } 1468 } 1469 1470 // Number parsed successfully; match prefix and 1471 // suffix to obtain multiplier 1472 pos.index = position; 1473 Number multiplier = computeParseMultiplier(text, pos, 1474 gotPositive ? matchedPosPrefix : matchedNegPrefix, 1475 status, gotPositive, gotNegative); 1476 1477 if (multiplier.longValue() == -1L) { 1478 return null; 1479 } else if (multiplier.longValue() != 1L) { 1480 cnfMultiplier = multiplier; 1481 } 1482 1483 // Special case INFINITY 1484 if (status[STATUS_INFINITE]) { 1485 if (status[STATUS_POSITIVE]) { 1486 return Double.POSITIVE_INFINITY; 1487 } else { 1488 return Double.NEGATIVE_INFINITY; 1489 } 1490 } 1491 1492 if (isParseBigDecimal()) { 1493 BigDecimal bigDecimalResult = digitList.getBigDecimal(); 1494 1495 if (cnfMultiplier.longValue() != 1) { 1496 bigDecimalResult = bigDecimalResult 1497 .multiply(new BigDecimal(cnfMultiplier.toString())); 1498 } 1499 if (!status[STATUS_POSITIVE]) { 1500 bigDecimalResult = bigDecimalResult.negate(); 1501 } 1502 return bigDecimalResult; 1503 } else { 1504 Number cnfResult; 1505 if (digitList.fitsIntoLong(status[STATUS_POSITIVE], isParseIntegerOnly())) { 1506 long longResult = digitList.getLong(); 1507 cnfResult = generateParseResult(longResult, false, 1508 longResult < 0, status, cnfMultiplier); 1509 } else { 1510 cnfResult = generateParseResult(digitList.getDouble(), 1511 true, false, status, cnfMultiplier); 1512 } 1513 return cnfResult; 1514 } 1515 } 1516 1517 /** 1518 * Returns the parsed result by multiplying the parsed number 1519 * with the multiplier representing the prefix and suffix. 1520 * 1521 * @param number parsed number component 1522 * @param gotDouble whether the parsed number contains decimal 1523 * @param gotLongMin whether the parsed number is Long.MIN 1524 * @param status boolean status flags indicating whether the 1525 * value is infinite and whether it is positive 1526 * @param cnfMultiplier compact number multiplier 1527 * @return parsed result 1528 */ 1529 private Number generateParseResult(Number number, boolean gotDouble, 1530 boolean gotLongMin, boolean[] status, Number cnfMultiplier) { 1531 1532 if (gotDouble) { 1533 if (cnfMultiplier.longValue() != 1L) { 1534 double doubleResult = number.doubleValue() * cnfMultiplier.doubleValue(); 1535 doubleResult = (double) convertIfNegative(doubleResult, status, gotLongMin); 1536 // Check if a double can be represeneted as a long 1537 long longResult = (long) doubleResult; 1538 gotDouble = ((doubleResult != (double) longResult) 1539 || (doubleResult == 0.0 && 1 / doubleResult < 0.0)); 1540 return gotDouble ? (Number) doubleResult : (Number) longResult; 1541 } 1542 } else { 1543 if (cnfMultiplier.longValue() != 1L) { 1544 Number result; 1545 if ((cnfMultiplier instanceof Long) && !gotLongMin) { 1546 long longMultiplier = (long) cnfMultiplier; 1547 try { 1548 result = Math.multiplyExact(number.longValue(), 1549 longMultiplier); 1550 } catch (ArithmeticException ex) { 1551 // If number * longMultiplier can not be represented 1552 // as long return as double 1553 result = number.doubleValue() * cnfMultiplier.doubleValue(); 1554 } 1555 } else { 1556 // cnfMultiplier can not be stored into long or the number 1557 // part is Long.MIN, return as double 1558 result = number.doubleValue() * cnfMultiplier.doubleValue(); 1559 } 1560 return convertIfNegative(result, status, gotLongMin); 1561 } 1562 } 1563 1564 // Default number 1565 return convertIfNegative(number, status, gotLongMin); 1566 } 1567 1568 /** 1569 * Negate the parsed value if the positive status flag is false 1570 * and the value is not a Long.MIN 1571 * @param number parsed value 1572 * @param status boolean status flags indicating whether the 1573 * value is infinite and whether it is positive 1574 * @param gotLongMin whether the parsed number is Long.MIN 1575 * @return the resulting value 1576 */ 1577 private Number convertIfNegative(Number number, boolean[] status, 1578 boolean gotLongMin) { 1579 1580 if (!status[STATUS_POSITIVE] && !gotLongMin) { 1581 if (number instanceof Long) { 1582 return -(long) number; 1583 } else { 1584 return -(double) number; 1585 } 1586 } else { 1587 return number; 1588 } 1589 } 1590 1591 /** 1592 * Attempts to match the given {@code affix} in the 1593 * specified {@code text}. 1594 */ 1595 private boolean matchAffix(String text, int position, String affix, 1596 String defaultAffix, String matchedAffix) { 1597 1598 // Check with the compact affixes which are non empty and 1599 // do not match with default affix 1600 if (!affix.isEmpty() && !affix.equals(defaultAffix)) { 1601 // Look ahead only for the longer match than the previous match 1602 if (matchedAffix.length() < affix.length()) { 1603 if (text.regionMatches(position, affix, 0, affix.length())) { 1604 return true; 1605 } 1606 } 1607 } 1608 return false; 1609 } 1610 1611 /** 1612 * Attempts to match given {@code prefix} and {@code suffix} in 1613 * the specified {@code text}. 1614 */ 1615 private boolean matchPrefixAndSuffix(String text, int position, String prefix, 1616 String matchedPrefix, String defaultPrefix, String suffix, 1617 String matchedSuffix, String defaultSuffix) { 1618 1619 // Check the compact pattern suffix only if there is a 1620 // compact prefix match or a default prefix match 1621 // because the compact prefix and suffix should match at the same 1622 // index to obtain the multiplier. 1623 // The prefix match is required because of the possibility of 1624 // same prefix at multiple index, in which case matching the suffix 1625 // is used to obtain the single match 1626 1627 if (prefix.equals(matchedPrefix) 1628 || matchedPrefix.equals(defaultPrefix)) { 1629 return matchAffix(text, position, suffix, defaultSuffix, matchedSuffix); 1630 } 1631 return false; 1632 } 1633 1634 /** 1635 * Computes multiplier by matching the given {@code matchedPrefix} 1636 * and suffix in the specified {@code text} from the lists of 1637 * prefixes and suffixes extracted from compact patterns. 1638 * 1639 * @param text the string to parse 1640 * @param parsePosition the {@code ParsePosition} object representing the 1641 * index and error index of the parse string 1642 * @param matchedPrefix prefix extracted which needs to be matched to 1643 * obtain the multiplier 1644 * @param status upon return contains boolean status flags indicating 1645 * whether the value is positive 1646 * @param gotPositive based on the prefix parsed; whether the number is positive 1647 * @param gotNegative based on the prefix parsed; whether the number is negative 1648 * @return the multiplier matching the prefix and suffix; -1 otherwise 1649 */ 1650 private Number computeParseMultiplier(String text, ParsePosition parsePosition, 1651 String matchedPrefix, boolean[] status, boolean gotPositive, 1652 boolean gotNegative) { 1653 1654 int position = parsePosition.index; 1655 boolean gotPos = false; 1656 boolean gotNeg = false; 1657 int matchedPosIndex = -1; 1658 int matchedNegIndex = -1; 1659 String matchedPosSuffix = ""; 1660 String matchedNegSuffix = ""; 1661 for (int compactIndex = 0; compactIndex < compactPatterns.length; compactIndex++) { 1662 String positivePrefix = positivePrefixes.get(compactIndex); 1663 String negativePrefix = negativePrefixes.get(compactIndex); 1664 String positiveSuffix = positiveSuffixes.get(compactIndex); 1665 String negativeSuffix = negativeSuffixes.get(compactIndex); 1666 1667 // Do not break if a match occur; there is a possibility that the 1668 // subsequent affixes may match the longer subsequence in the given 1669 // string. 1670 // For example, matching "3Mdx" with "M", "Md" should match with "Md" 1671 boolean match = matchPrefixAndSuffix(text, position, positivePrefix, matchedPrefix, 1672 defaultDecimalFormat.getPositivePrefix(), positiveSuffix, 1673 matchedPosSuffix, defaultDecimalFormat.getPositiveSuffix()); 1674 if (match) { 1675 matchedPosIndex = compactIndex; 1676 matchedPosSuffix = positiveSuffix; 1677 gotPos = true; 1678 } 1679 1680 match = matchPrefixAndSuffix(text, position, negativePrefix, matchedPrefix, 1681 defaultDecimalFormat.getNegativePrefix(), negativeSuffix, 1682 matchedNegSuffix, defaultDecimalFormat.getNegativeSuffix()); 1683 if (match) { 1684 matchedNegIndex = compactIndex; 1685 matchedNegSuffix = negativeSuffix; 1686 gotNeg = true; 1687 } 1688 } 1689 1690 // Suffix in the given text does not match with the compact 1691 // patterns suffixes; match with the default suffix 1692 if (!gotPos && !gotNeg) { 1693 String positiveSuffix = defaultDecimalFormat.getPositiveSuffix(); 1694 String negativeSuffix = defaultDecimalFormat.getNegativeSuffix(); 1695 if (text.regionMatches(position, positiveSuffix, 0, 1696 positiveSuffix.length())) { 1697 // Matches the default positive prefix 1698 matchedPosSuffix = positiveSuffix; 1699 gotPos = true; 1700 } 1701 if (text.regionMatches(position, negativeSuffix, 0, 1702 negativeSuffix.length())) { 1703 // Matches the default negative suffix 1704 matchedNegSuffix = negativeSuffix; 1705 gotNeg = true; 1706 } 1707 } 1708 1709 // If both matches, take the longest one 1710 if (gotPos && gotNeg) { 1711 if (matchedPosSuffix.length() > matchedNegSuffix.length()) { 1712 gotNeg = false; 1713 } else if (matchedPosSuffix.length() < matchedNegSuffix.length()) { 1714 gotPos = false; 1715 } else { 1716 // If longest comparison fails; take the positive and negative 1717 // sign of matching prefix 1718 gotPos = gotPositive; 1719 gotNeg = gotNegative; 1720 } 1721 } 1722 1723 // Fail if neither or both 1724 if (gotPos == gotNeg) { 1725 parsePosition.errorIndex = position; 1726 return -1L; 1727 } 1728 1729 Number cnfMultiplier; 1730 // Update the parse position index and take compact multiplier 1731 // only if it matches the compact suffix, not the default 1732 // suffix; else multiplier should be 1 1733 if (gotPos) { 1734 parsePosition.index = position + matchedPosSuffix.length(); 1735 cnfMultiplier = matchedPosIndex != -1 1736 ? divisors.get(matchedPosIndex) : 1L; 1737 } else { 1738 parsePosition.index = position + matchedNegSuffix.length(); 1739 cnfMultiplier = matchedNegIndex != -1 1740 ? divisors.get(matchedNegIndex) : 1L; 1741 } 1742 status[STATUS_POSITIVE] = gotPos; 1743 return cnfMultiplier; 1744 } 1745 1746 /** 1747 * Reconstitutes this {@code CompactNumberFormat} from a stream 1748 * (that is, deserializes it) after performing some validations. 1749 * This method throws InvalidObjectException, if the stream data is invalid 1750 * because of the following reasons, 1751 * <ul> 1752 * <li> If any of the {@code decimalPattern}, {@code compactPatterns}, 1753 * {@code symbols} or {@code roundingMode} is {@code null}. 1754 * <li> If the {@code decimalPattern} or the {@code compactPatterns} array 1755 * contains an invalid pattern or if a {@code null} appears in the array of 1756 * compact patterns. 1757 * <li> If the {@code minimumIntegerDigits} is greater than the 1758 * {@code maximumIntegerDigits} or the {@code minimumFractionDigits} is 1759 * greater than the {@code maximumFractionDigits}. This check is performed 1760 * by superclass's Object. 1761 * <li> If any of the minimum/maximum integer/fraction digit count is 1762 * negative. This check is performed by superclass's readObject. 1763 * <li> If the minimum or maximum integer digit count is larger than 309 or 1764 * if the minimum or maximum fraction digit count is larger than 340. 1765 * <li> If the grouping size is negative or larger than 127. 1766 * </ul> 1767 * 1768 * @param inStream the stream 1769 * @throws IOException if an I/O error occurs 1770 * @throws ClassNotFoundException if the class of a serialized object 1771 * could not be found 1772 */ 1773 private void readObject(ObjectInputStream inStream) throws IOException, 1774 ClassNotFoundException { 1775 1776 inStream.defaultReadObject(); 1777 if (decimalPattern == null || compactPatterns == null 1778 || symbols == null || roundingMode == null) { 1779 throw new InvalidObjectException("One of the 'decimalPattern'," 1780 + " 'compactPatterns', 'symbols' or 'roundingMode'" 1781 + " is null"); 1782 } 1783 1784 // Check only the maximum counts because NumberFormat.readObject has 1785 // already ensured that the maximum is greater than the minimum count. 1786 if (getMaximumIntegerDigits() > DecimalFormat.DOUBLE_INTEGER_DIGITS 1787 || getMaximumFractionDigits() > DecimalFormat.DOUBLE_FRACTION_DIGITS) { 1788 throw new InvalidObjectException("Digit count out of range"); 1789 } 1790 1791 // Check if the grouping size is negative, on an attempt to 1792 // put value > 127, it wraps around, so check just negative value 1793 if (groupingSize < 0) { 1794 throw new InvalidObjectException("Grouping size is negative"); 1795 } 1796 1797 try { 1798 processCompactPatterns(); 1799 } catch (IllegalArgumentException ex) { 1800 throw new InvalidObjectException(ex.getMessage()); 1801 } 1802 1803 decimalFormat = new DecimalFormat(SPECIAL_PATTERN, symbols); 1804 decimalFormat.setMaximumFractionDigits(getMaximumFractionDigits()); 1805 decimalFormat.setMinimumFractionDigits(getMinimumFractionDigits()); 1806 decimalFormat.setMaximumIntegerDigits(getMaximumIntegerDigits()); 1807 decimalFormat.setMinimumIntegerDigits(getMinimumIntegerDigits()); 1808 decimalFormat.setRoundingMode(getRoundingMode()); 1809 decimalFormat.setGroupingSize(getGroupingSize()); 1810 decimalFormat.setGroupingUsed(isGroupingUsed()); 1811 decimalFormat.setParseIntegerOnly(isParseIntegerOnly()); 1812 1813 try { 1814 defaultDecimalFormat = new DecimalFormat(decimalPattern, symbols); 1815 defaultDecimalFormat.setMaximumFractionDigits(0); 1816 } catch (IllegalArgumentException ex) { 1817 throw new InvalidObjectException(ex.getMessage()); 1818 } 1819 1820 } 1821 1822 /** 1823 * Sets the maximum number of digits allowed in the integer portion of a 1824 * number. 1825 * The maximum allowed integer range is 309, if the {@code newValue} > 309, 1826 * then the maximum integer digits count is set to 309. Negative input 1827 * values are replaced with 0. 1828 * 1829 * @param newValue the maximum number of integer digits to be shown 1830 * @see #getMaximumIntegerDigits() 1831 */ 1832 @Override 1833 public void setMaximumIntegerDigits(int newValue) { 1834 // The maximum integer digits is checked with the allowed range before calling 1835 // the DecimalFormat.setMaximumIntegerDigits, which performs the negative check 1836 // on the given newValue while setting it as max integer digits. 1837 // For example, if a negative value is specified, it is replaced with 0 1838 decimalFormat.setMaximumIntegerDigits(Math.min(newValue, 1839 DecimalFormat.DOUBLE_INTEGER_DIGITS)); 1840 super.setMaximumIntegerDigits(decimalFormat.getMaximumIntegerDigits()); 1841 if (decimalFormat.getMinimumIntegerDigits() > decimalFormat.getMaximumIntegerDigits()) { 1842 decimalFormat.setMinimumIntegerDigits(decimalFormat.getMaximumIntegerDigits()); 1843 super.setMinimumIntegerDigits(decimalFormat.getMinimumIntegerDigits()); 1844 } 1845 } 1846 1847 /** 1848 * Sets the minimum number of digits allowed in the integer portion of a 1849 * number. 1850 * The maximum allowed integer range is 309, if the {@code newValue} > 309, 1851 * then the minimum integer digits count is set to 309. Negative input 1852 * values are replaced with 0. 1853 * 1854 * @param newValue the minimum number of integer digits to be shown 1855 * @see #getMinimumIntegerDigits() 1856 */ 1857 @Override 1858 public void setMinimumIntegerDigits(int newValue) { 1859 // The minimum integer digits is checked with the allowed range before calling 1860 // the DecimalFormat.setMinimumIntegerDigits, which performs check on the given 1861 // newValue while setting it as min integer digits. For example, if a negative 1862 // value is specified, it is replaced with 0 1863 decimalFormat.setMinimumIntegerDigits(Math.min(newValue, 1864 DecimalFormat.DOUBLE_INTEGER_DIGITS)); 1865 super.setMinimumIntegerDigits(decimalFormat.getMinimumIntegerDigits()); 1866 if (decimalFormat.getMinimumIntegerDigits() > decimalFormat.getMaximumIntegerDigits()) { 1867 decimalFormat.setMaximumIntegerDigits(decimalFormat.getMinimumIntegerDigits()); 1868 super.setMaximumIntegerDigits(decimalFormat.getMaximumIntegerDigits()); 1869 } 1870 } 1871 1872 /** 1873 * Sets the minimum number of digits allowed in the fraction portion of a 1874 * number. 1875 * The maximum allowed fraction range is 340, if the {@code newValue} > 340, 1876 * then the minimum fraction digits count is set to 340. Negative input 1877 * values are replaced with 0. 1878 * 1879 * @param newValue the minimum number of fraction digits to be shown 1880 * @see #getMinimumFractionDigits() 1881 */ 1882 @Override 1883 public void setMinimumFractionDigits(int newValue) { 1884 // The minimum fraction digits is checked with the allowed range before 1885 // calling the DecimalFormat.setMinimumFractionDigits, which performs 1886 // check on the given newValue while setting it as min fraction 1887 // digits. For example, if a negative value is specified, it is 1888 // replaced with 0 1889 decimalFormat.setMinimumFractionDigits(Math.min(newValue, 1890 DecimalFormat.DOUBLE_FRACTION_DIGITS)); 1891 super.setMinimumFractionDigits(decimalFormat.getMinimumFractionDigits()); 1892 if (decimalFormat.getMinimumFractionDigits() > decimalFormat.getMaximumFractionDigits()) { 1893 decimalFormat.setMaximumFractionDigits(decimalFormat.getMinimumFractionDigits()); 1894 super.setMaximumFractionDigits(decimalFormat.getMaximumFractionDigits()); 1895 } 1896 } 1897 1898 /** 1899 * Sets the maximum number of digits allowed in the fraction portion of a 1900 * number. 1901 * The maximum allowed fraction range is 340, if the {@code newValue} > 340, 1902 * then the maximum fraction digits count is set to 340. Negative input 1903 * values are replaced with 0. 1904 * 1905 * @param newValue the maximum number of fraction digits to be shown 1906 * @see #getMaximumFractionDigits() 1907 */ 1908 @Override 1909 public void setMaximumFractionDigits(int newValue) { 1910 // The maximum fraction digits is checked with the allowed range before 1911 // calling the DecimalFormat.setMaximumFractionDigits, which performs 1912 // check on the given newValue while setting it as max fraction digits. 1913 // For example, if a negative value is specified, it is replaced with 0 1914 decimalFormat.setMaximumFractionDigits(Math.min(newValue, 1915 DecimalFormat.DOUBLE_FRACTION_DIGITS)); 1916 super.setMaximumFractionDigits(decimalFormat.getMaximumFractionDigits()); 1917 if (decimalFormat.getMinimumFractionDigits() > decimalFormat.getMaximumFractionDigits()) { 1918 decimalFormat.setMinimumFractionDigits(decimalFormat.getMaximumFractionDigits()); 1919 super.setMinimumFractionDigits(decimalFormat.getMinimumFractionDigits()); 1920 } 1921 } 1922 1923 /** 1924 * Gets the {@link java.math.RoundingMode} used in this 1925 * {@code CompactNumberFormat}. 1926 * 1927 * @return the {@code RoundingMode} used for this 1928 * {@code CompactNumberFormat} 1929 * @see #setRoundingMode(RoundingMode) 1930 */ 1931 @Override 1932 public RoundingMode getRoundingMode() { 1933 return roundingMode; 1934 } 1935 1936 /** 1937 * Sets the {@link java.math.RoundingMode} used in this 1938 * {@code CompactNumberFormat}. 1939 * 1940 * @param roundingMode the {@code RoundingMode} to be used 1941 * @see #getRoundingMode() 1942 * @throws NullPointerException if {@code roundingMode} is {@code null} 1943 */ 1944 @Override 1945 public void setRoundingMode(RoundingMode roundingMode) { 1946 decimalFormat.setRoundingMode(roundingMode); 1947 this.roundingMode = roundingMode; 1948 } 1949 1950 /** 1951 * Returns the grouping size. Grouping size is the number of digits between 1952 * grouping separators in the integer portion of a number. For example, 1953 * in the compact number {@code "12,347 trillion"} for the 1954 * {@link java.util.Locale#US US locale}, the grouping size is 3. 1955 * 1956 * @return the grouping size 1957 * @see #setGroupingSize 1958 * @see java.text.NumberFormat#isGroupingUsed 1959 * @see java.text.DecimalFormatSymbols#getGroupingSeparator 1960 */ 1961 public int getGroupingSize() { 1962 return groupingSize; 1963 } 1964 1965 /** 1966 * Sets the grouping size. Grouping size is the number of digits between 1967 * grouping separators in the integer portion of a number. For example, 1968 * in the compact number {@code "12,347 trillion"} for the 1969 * {@link java.util.Locale#US US locale}, the grouping size is 3. The grouping 1970 * size must be greater than or equal to zero and less than or equal to 127. 1971 * 1972 * @param newValue the new grouping size 1973 * @see #getGroupingSize 1974 * @see java.text.NumberFormat#setGroupingUsed 1975 * @see java.text.DecimalFormatSymbols#setGroupingSeparator 1976 * @throws IllegalArgumentException if {@code newValue} is negative or 1977 * larger than 127 1978 */ 1979 public void setGroupingSize(int newValue) { 1980 if (newValue < 0 || newValue > 127) { 1981 throw new IllegalArgumentException( 1982 "The value passed is negative or larger than 127"); 1983 } 1984 groupingSize = (byte) newValue; 1985 decimalFormat.setGroupingSize(groupingSize); 1986 } 1987 1988 /** 1989 * Returns true if grouping is used in this format. For example, with 1990 * grouping on and grouping size set to 3, the number {@code 12346567890987654} 1991 * can be formatted as {@code "12,347 trillion"} in the 1992 * {@link java.util.Locale#US US locale}. 1993 * The grouping separator is locale dependent. 1994 * 1995 * @return {@code true} if grouping is used; 1996 * {@code false} otherwise 1997 * @see #setGroupingUsed 1998 */ 1999 @Override 2000 public boolean isGroupingUsed() { 2001 return super.isGroupingUsed(); 2002 } 2003 2004 /** 2005 * Sets whether or not grouping will be used in this format. 2006 * 2007 * @param newValue {@code true} if grouping is used; 2008 * {@code false} otherwise 2009 * @see #isGroupingUsed 2010 */ 2011 @Override 2012 public void setGroupingUsed(boolean newValue) { 2013 decimalFormat.setGroupingUsed(newValue); 2014 super.setGroupingUsed(newValue); 2015 } 2016 2017 /** 2018 * Returns true if this format parses only an integer from the number 2019 * component of a compact number. 2020 * Parsing an integer means that only an integer is considered from the 2021 * number component, prefix/suffix is still considered to compute the 2022 * resulting output. 2023 * For example, in the {@link java.util.Locale#US US locale}, if this method 2024 * returns {@code true}, the string {@code "1234.78 thousand"} would be 2025 * parsed as the value {@code 1234000} (1234 (integer part) * 1000 2026 * (thousand)) and the fractional part would be skipped. 2027 * The exact format accepted by the parse operation is locale dependent. 2028 * 2029 * @return {@code true} if compact numbers should be parsed as integers 2030 * only; {@code false} otherwise 2031 */ 2032 @Override 2033 public boolean isParseIntegerOnly() { 2034 return super.isParseIntegerOnly(); 2035 } 2036 2037 /** 2038 * Sets whether or not this format parses only an integer from the number 2039 * component of a compact number. 2040 * 2041 * @param value {@code true} if compact numbers should be parsed as 2042 * integers only; {@code false} otherwise 2043 * @see #isParseIntegerOnly 2044 */ 2045 @Override 2046 public void setParseIntegerOnly(boolean value) { 2047 decimalFormat.setParseIntegerOnly(value); 2048 super.setParseIntegerOnly(value); 2049 } 2050 2051 /** 2052 * Returns whether the {@link #parse(String, ParsePosition)} 2053 * method returns {@code BigDecimal}. The default value is false. 2054 * 2055 * @return {@code true} if the parse method returns BigDecimal; 2056 * {@code false} otherwise 2057 * @see #setParseBigDecimal 2058 * 2059 */ 2060 public boolean isParseBigDecimal() { 2061 return parseBigDecimal; 2062 } 2063 2064 /** 2065 * Sets whether the {@link #parse(String, ParsePosition)} 2066 * method returns {@code BigDecimal}. 2067 * 2068 * @param newValue {@code true} if the parse method returns BigDecimal; 2069 * {@code false} otherwise 2070 * @see #isParseBigDecimal 2071 * 2072 */ 2073 public void setParseBigDecimal(boolean newValue) { 2074 parseBigDecimal = newValue; 2075 } 2076 2077 /** 2078 * Checks if this {@code CompactNumberFormat} is equal to the 2079 * specified {@code obj}. The objects of type {@code CompactNumberFormat} 2080 * are compared, other types return false; obeys the general contract of 2081 * {@link java.lang.Object#equals(java.lang.Object) Object.equals}. 2082 * 2083 * @param obj the object to compare with 2084 * @return true if this is equal to the other {@code CompactNumberFormat} 2085 */ 2086 @Override 2087 public boolean equals(Object obj) { 2088 2089 if (!super.equals(obj)) { 2090 return false; 2091 } 2092 2093 CompactNumberFormat other = (CompactNumberFormat) obj; 2094 return decimalPattern.equals(other.decimalPattern) 2095 && symbols.equals(other.symbols) 2096 && Arrays.equals(compactPatterns, other.compactPatterns) 2097 && roundingMode.equals(other.roundingMode) 2098 && groupingSize == other.groupingSize 2099 && parseBigDecimal == other.parseBigDecimal; 2100 } 2101 2102 /** 2103 * Returns the hash code for this {@code CompactNumberFormat} instance. 2104 * 2105 * @return hash code for this {@code CompactNumberFormat} 2106 */ 2107 @Override 2108 public int hashCode() { 2109 return 31 * super.hashCode() + 2110 Objects.hash(decimalPattern, symbols, roundingMode) 2111 + Arrays.hashCode(compactPatterns) + groupingSize 2112 + Boolean.hashCode(parseBigDecimal); 2113 } 2114 2115 /** 2116 * Creates and returns a copy of this {@code CompactNumberFormat} 2117 * instance. 2118 * 2119 * @return a clone of this instance 2120 */ 2121 @Override 2122 public CompactNumberFormat clone() { 2123 CompactNumberFormat other = (CompactNumberFormat) super.clone(); 2124 other.compactPatterns = compactPatterns.clone(); 2125 other.symbols = (DecimalFormatSymbols) symbols.clone(); 2126 return other; 2127 } 2128 2129 } 2130