1 /* 2 * Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 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 != null ? number.getClass().getName() : null) + " 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 if (pattern == null) { 1057 throw new IllegalArgumentException("A null compact pattern" + 1058 " encountered at index: " + index); 1059 } 1060 1061 int start = 0; 1062 boolean gotNegative = false; 1063 1064 String positivePrefix = ""; 1065 String positiveSuffix = ""; 1066 String negativePrefix = ""; 1067 String negativeSuffix = ""; 1068 String zeros = ""; 1069 for (int j = 1; j >= 0 && start < pattern.length(); --j) { 1070 1071 StringBuffer prefix = new StringBuffer(); 1072 StringBuffer suffix = new StringBuffer(); 1073 boolean inQuote = false; 1074 // The phase ranges from 0 to 2. Phase 0 is the prefix. Phase 1 is 1075 // the section of the pattern with digits. Phase 2 is the suffix. 1076 // The separation of the characters into phases is 1077 // strictly enforced; if phase 1 characters are to appear in the 1078 // suffix, for example, they must be quoted. 1079 int phase = 0; 1080 1081 // The affix is either the prefix or the suffix. 1082 StringBuffer affix = prefix; 1083 1084 for (int pos = start; pos < pattern.length(); ++pos) { 1085 char ch = pattern.charAt(pos); 1086 switch (phase) { 1087 case 0: 1088 case 2: 1089 // Process the prefix / suffix characters 1090 if (inQuote) { 1091 // A quote within quotes indicates either the closing 1092 // quote or two quotes, which is a quote literal. That 1093 // is, we have the second quote in 'do' or 'don''t'. 1094 if (ch == QUOTE) { 1095 if ((pos + 1) < pattern.length() 1096 && pattern.charAt(pos + 1) == QUOTE) { 1097 ++pos; 1098 affix.append("''"); // 'don''t' 1099 } else { 1100 inQuote = false; // 'do' 1101 } 1102 continue; 1103 } 1104 } else { 1105 // Process unquoted characters seen in prefix or suffix 1106 // phase. 1107 switch (ch) { 1108 case ZERO_DIGIT: 1109 phase = 1; 1110 --pos; // Reprocess this character 1111 continue; 1112 case QUOTE: 1113 // A quote outside quotes indicates either the 1114 // opening quote or two quotes, which is a quote 1115 // literal. That is, we have the first quote in 'do' 1116 // or o''clock. 1117 if ((pos + 1) < pattern.length() 1118 && pattern.charAt(pos + 1) == QUOTE) { 1119 ++pos; 1120 affix.append("''"); // o''clock 1121 } else { 1122 inQuote = true; // 'do' 1123 } 1124 continue; 1125 case SEPARATOR: 1126 // Don't allow separators before we see digit 1127 // characters of phase 1, and don't allow separators 1128 // in the second pattern (j == 0). 1129 if (phase == 0 || j == 0) { 1130 throw new IllegalArgumentException( 1131 "Unquoted special character '" 1132 + ch + "' in pattern \"" + pattern + "\""); 1133 } 1134 start = pos + 1; 1135 pos = pattern.length(); 1136 continue; 1137 case MINUS_SIGN: 1138 affix.append("'-"); 1139 continue; 1140 case DECIMAL_SEPARATOR: 1141 case GROUPING_SEPARATOR: 1142 case DIGIT: 1143 case PERCENT: 1144 case PER_MILLE: 1145 case CURRENCY_SIGN: 1146 throw new IllegalArgumentException( 1147 "Unquoted special character '" + ch 1148 + "' in pattern \"" + pattern + "\""); 1149 default: 1150 break; 1151 } 1152 } 1153 // Note that if we are within quotes, or if this is an 1154 // unquoted, non-special character, then we usually fall 1155 // through to here. 1156 affix.append(ch); 1157 break; 1158 1159 case 1: 1160 // The negative subpattern (j = 0) serves only to specify the 1161 // negative prefix and suffix, so all the phase 1 characters, 1162 // for example, digits, zeroDigit, groupingSeparator, 1163 // decimalSeparator, exponent are ignored 1164 if (j == 0) { 1165 while (pos < pattern.length()) { 1166 char negPatternChar = pattern.charAt(pos); 1167 if (negPatternChar == ZERO_DIGIT) { 1168 ++pos; 1169 } else { 1170 // Not a phase 1 character, consider it as 1171 // suffix and parse it in phase 2 1172 --pos; //process it again in outer loop 1173 phase = 2; 1174 affix = suffix; 1175 break; 1176 } 1177 } 1178 continue; 1179 } 1180 // Consider only '0' as valid pattern char which can appear 1181 // in number part, rest can be either suffix or prefix 1182 if (ch == ZERO_DIGIT) { 1183 zeros = zeros + "0"; 1184 } else { 1185 phase = 2; 1186 affix = suffix; 1187 --pos; 1188 } 1189 break; 1190 } 1191 } 1192 1193 if (inQuote) { 1194 throw new IllegalArgumentException("Invalid single quote" 1195 + " in pattern \"" + pattern + "\""); 1196 } 1197 1198 if (j == 1) { 1199 positivePrefix = prefix.toString(); 1200 positiveSuffix = suffix.toString(); 1201 negativePrefix = positivePrefix; 1202 negativeSuffix = positiveSuffix; 1203 } else { 1204 negativePrefix = prefix.toString(); 1205 negativeSuffix = suffix.toString(); 1206 gotNegative = true; 1207 } 1208 1209 // If there is no negative pattern, or if the negative pattern is 1210 // identical to the positive pattern, then prepend the minus sign to 1211 // the positive pattern to form the negative pattern. 1212 if (!gotNegative 1213 || (negativePrefix.equals(positivePrefix) 1214 && negativeSuffix.equals(positiveSuffix))) { 1215 negativeSuffix = positiveSuffix; 1216 negativePrefix = "'-" + positivePrefix; 1217 } 1218 } 1219 1220 // If no 0s are specified in a non empty pattern, it is invalid 1221 if (!pattern.isEmpty() && zeros.isEmpty()) { 1222 throw new IllegalArgumentException("Invalid pattern" 1223 + " [" + pattern + "]: all patterns must include digit" 1224 + " placement 0s"); 1225 } 1226 1227 // Only if positive affix exists; else put empty strings 1228 if (!positivePrefix.isEmpty() || !positiveSuffix.isEmpty()) { 1229 positivePrefixPatterns.add(positivePrefix); 1230 negativePrefixPatterns.add(negativePrefix); 1231 positiveSuffixPatterns.add(positiveSuffix); 1232 negativeSuffixPatterns.add(negativeSuffix); 1233 divisors.add(computeDivisor(zeros, index)); 1234 } else { 1235 positivePrefixPatterns.add(""); 1236 negativePrefixPatterns.add(""); 1237 positiveSuffixPatterns.add(""); 1238 negativeSuffixPatterns.add(""); 1239 divisors.add(1L); 1240 } 1241 } 1242 1243 private final transient DigitList digitList = new DigitList(); 1244 private static final int STATUS_INFINITE = 0; 1245 private static final int STATUS_POSITIVE = 1; 1246 private static final int STATUS_LENGTH = 2; 1247 1248 private static final char ZERO_DIGIT = '0'; 1249 private static final char DIGIT = '#'; 1250 private static final char DECIMAL_SEPARATOR = '.'; 1251 private static final char GROUPING_SEPARATOR = ','; 1252 private static final char MINUS_SIGN = '-'; 1253 private static final char PERCENT = '%'; 1254 private static final char PER_MILLE = '\u2030'; 1255 private static final char SEPARATOR = ';'; 1256 private static final char CURRENCY_SIGN = '\u00A4'; 1257 private static final char QUOTE = '\''; 1258 1259 // Expanded form of positive/negative prefix/suffix, 1260 // the expanded form contains special characters in 1261 // its localized form, which are used for matching 1262 // while parsing a string to number 1263 private transient List<String> positivePrefixes; 1264 private transient List<String> negativePrefixes; 1265 private transient List<String> positiveSuffixes; 1266 private transient List<String> negativeSuffixes; 1267 1268 private void expandAffixPatterns() { 1269 positivePrefixes = new ArrayList<>(compactPatterns.length); 1270 negativePrefixes = new ArrayList<>(compactPatterns.length); 1271 positiveSuffixes = new ArrayList<>(compactPatterns.length); 1272 negativeSuffixes = new ArrayList<>(compactPatterns.length); 1273 for (int index = 0; index < compactPatterns.length; index++) { 1274 positivePrefixes.add(expandAffix(positivePrefixPatterns.get(index))); 1275 negativePrefixes.add(expandAffix(negativePrefixPatterns.get(index))); 1276 positiveSuffixes.add(expandAffix(positiveSuffixPatterns.get(index))); 1277 negativeSuffixes.add(expandAffix(negativeSuffixPatterns.get(index))); 1278 } 1279 } 1280 1281 /** 1282 * Parses a compact number from a string to produce a {@code Number}. 1283 * <p> 1284 * The method attempts to parse text starting at the index given by 1285 * {@code pos}. 1286 * If parsing succeeds, then the index of {@code pos} is updated 1287 * to the index after the last character used (parsing does not necessarily 1288 * use all characters up to the end of the string), and the parsed 1289 * number is returned. The updated {@code pos} can be used to 1290 * indicate the starting point for the next call to this method. 1291 * If an error occurs, then the index of {@code pos} is not 1292 * changed, the error index of {@code pos} is set to the index of 1293 * the character where the error occurred, and {@code null} is returned. 1294 * <p> 1295 * The value is the numeric part in the given text multiplied 1296 * by the numeric equivalent of the affix attached 1297 * (For example, "K" = 1000 in {@link java.util.Locale#US US locale}). 1298 * The subclass returned depends on the value of 1299 * {@link #isParseBigDecimal}. 1300 * <ul> 1301 * <li>If {@link #isParseBigDecimal()} is false (the default), 1302 * most integer values are returned as {@code Long} 1303 * objects, no matter how they are written: {@code "17K"} and 1304 * {@code "17.000K"} both parse to {@code Long.valueOf(17000)}. 1305 * If the value cannot fit into {@code Long}, then the result is 1306 * returned as {@code Double}. This includes values with a 1307 * fractional part, infinite values, {@code NaN}, 1308 * and the value -0.0. 1309 * <p> 1310 * Callers may use the {@code Number} methods {@code doubleValue}, 1311 * {@code longValue}, etc., to obtain the type they want. 1312 * 1313 * <li>If {@link #isParseBigDecimal()} is true, values are returned 1314 * as {@code BigDecimal} objects. The special cases negative 1315 * and positive infinity and NaN are returned as {@code Double} 1316 * instances holding the values of the corresponding 1317 * {@code Double} constants. 1318 * </ul> 1319 * <p> 1320 * {@code CompactNumberFormat} parses all Unicode characters that represent 1321 * decimal digits, as defined by {@code Character.digit()}. In 1322 * addition, {@code CompactNumberFormat} also recognizes as digits the ten 1323 * consecutive characters starting with the localized zero digit defined in 1324 * the {@code DecimalFormatSymbols} object. 1325 * <p> 1326 * {@code CompactNumberFormat} parse does not allow parsing scientific 1327 * notations. For example, parsing a string {@code "1.05E4K"} in 1328 * {@link java.util.Locale#US US locale} breaks at character 'E' 1329 * and returns 1.05. 1330 * 1331 * @param text the string to be parsed 1332 * @param pos a {@code ParsePosition} object with index and error 1333 * index information as described above 1334 * @return the parsed value, or {@code null} if the parse fails 1335 * @exception NullPointerException if {@code text} or 1336 * {@code pos} is null 1337 * 1338 */ 1339 @Override 1340 public Number parse(String text, ParsePosition pos) { 1341 1342 Objects.requireNonNull(text); 1343 Objects.requireNonNull(pos); 1344 1345 // Lazily expanding the affix patterns, on the first parse 1346 // call on this instance 1347 // If not initialized, expand and load all affixes 1348 if (positivePrefixes == null) { 1349 expandAffixPatterns(); 1350 } 1351 1352 // The compact number multiplier for parsed string. 1353 // Its value is set on parsing prefix and suffix. For example, 1354 // in the {@link java.util.Locale#US US locale} parsing {@code "1K"} 1355 // sets its value to 1000, as K (thousand) is abbreviated form of 1000. 1356 Number cnfMultiplier = 1L; 1357 1358 // Special case NaN 1359 if (text.regionMatches(pos.index, symbols.getNaN(), 1360 0, symbols.getNaN().length())) { 1361 pos.index = pos.index + symbols.getNaN().length(); 1362 return Double.NaN; 1363 } 1364 1365 int position = pos.index; 1366 int oldStart = pos.index; 1367 boolean gotPositive = false; 1368 boolean gotNegative = false; 1369 int matchedPosIndex = -1; 1370 int matchedNegIndex = -1; 1371 String matchedPosPrefix = ""; 1372 String matchedNegPrefix = ""; 1373 String defaultPosPrefix = defaultDecimalFormat.getPositivePrefix(); 1374 String defaultNegPrefix = defaultDecimalFormat.getNegativePrefix(); 1375 // Prefix matching 1376 for (int compactIndex = 0; compactIndex < compactPatterns.length; compactIndex++) { 1377 String positivePrefix = positivePrefixes.get(compactIndex); 1378 String negativePrefix = negativePrefixes.get(compactIndex); 1379 1380 // Do not break if a match occur; there is a possibility that the 1381 // subsequent affixes may match the longer subsequence in the given 1382 // string. 1383 // For example, matching "Mdx 3" with "M", "Md" as prefix should 1384 // match with "Md" 1385 boolean match = matchAffix(text, position, positivePrefix, 1386 defaultPosPrefix, matchedPosPrefix); 1387 if (match) { 1388 matchedPosIndex = compactIndex; 1389 matchedPosPrefix = positivePrefix; 1390 gotPositive = true; 1391 } 1392 1393 match = matchAffix(text, position, negativePrefix, 1394 defaultNegPrefix, matchedNegPrefix); 1395 if (match) { 1396 matchedNegIndex = compactIndex; 1397 matchedNegPrefix = negativePrefix; 1398 gotNegative = true; 1399 } 1400 } 1401 1402 // Given text does not match the non empty valid compact prefixes 1403 // check with the default prefixes 1404 if (!gotPositive && !gotNegative) { 1405 if (text.regionMatches(pos.index, defaultPosPrefix, 0, 1406 defaultPosPrefix.length())) { 1407 // Matches the default positive prefix 1408 matchedPosPrefix = defaultPosPrefix; 1409 gotPositive = true; 1410 } 1411 if (text.regionMatches(pos.index, defaultNegPrefix, 0, 1412 defaultNegPrefix.length())) { 1413 // Matches the default negative prefix 1414 matchedNegPrefix = defaultNegPrefix; 1415 gotNegative = true; 1416 } 1417 } 1418 1419 // If both match, take the longest one 1420 if (gotPositive && gotNegative) { 1421 if (matchedPosPrefix.length() > matchedNegPrefix.length()) { 1422 gotNegative = false; 1423 } else if (matchedPosPrefix.length() < matchedNegPrefix.length()) { 1424 gotPositive = false; 1425 } 1426 } 1427 1428 // Update the position and take compact multiplier 1429 // only if it matches the compact prefix, not the default 1430 // prefix; else multiplier should be 1 1431 if (gotPositive) { 1432 position += matchedPosPrefix.length(); 1433 cnfMultiplier = matchedPosIndex != -1 1434 ? divisors.get(matchedPosIndex) : 1L; 1435 } else if (gotNegative) { 1436 position += matchedNegPrefix.length(); 1437 cnfMultiplier = matchedNegIndex != -1 1438 ? divisors.get(matchedNegIndex) : 1L; 1439 } 1440 1441 digitList.setRoundingMode(getRoundingMode()); 1442 boolean[] status = new boolean[STATUS_LENGTH]; 1443 1444 // Call DecimalFormat.subparseNumber() method to parse the 1445 // number part of the input text 1446 position = decimalFormat.subparseNumber(text, position, 1447 digitList, false, false, status); 1448 1449 if (position == -1) { 1450 // Unable to parse the number successfully 1451 pos.index = oldStart; 1452 pos.errorIndex = oldStart; 1453 return null; 1454 } 1455 1456 // If parse integer only is true and the parsing is broken at 1457 // decimal point, then pass/ignore all digits and move pointer 1458 // at the start of suffix, to process the suffix part 1459 if (isParseIntegerOnly() 1460 && text.charAt(position) == symbols.getDecimalSeparator()) { 1461 position++; // Pass decimal character 1462 for (; position < text.length(); ++position) { 1463 char ch = text.charAt(position); 1464 int digit = ch - symbols.getZeroDigit(); 1465 if (digit < 0 || digit > 9) { 1466 digit = Character.digit(ch, 10); 1467 // Parse all digit characters 1468 if (!(digit >= 0 && digit <= 9)) { 1469 break; 1470 } 1471 } 1472 } 1473 } 1474 1475 // Number parsed successfully; match prefix and 1476 // suffix to obtain multiplier 1477 pos.index = position; 1478 Number multiplier = computeParseMultiplier(text, pos, 1479 gotPositive ? matchedPosPrefix : matchedNegPrefix, 1480 status, gotPositive, gotNegative); 1481 1482 if (multiplier.longValue() == -1L) { 1483 return null; 1484 } else if (multiplier.longValue() != 1L) { 1485 cnfMultiplier = multiplier; 1486 } 1487 1488 // Special case INFINITY 1489 if (status[STATUS_INFINITE]) { 1490 if (status[STATUS_POSITIVE]) { 1491 return Double.POSITIVE_INFINITY; 1492 } else { 1493 return Double.NEGATIVE_INFINITY; 1494 } 1495 } 1496 1497 if (isParseBigDecimal()) { 1498 BigDecimal bigDecimalResult = digitList.getBigDecimal(); 1499 1500 if (cnfMultiplier.longValue() != 1) { 1501 bigDecimalResult = bigDecimalResult 1502 .multiply(new BigDecimal(cnfMultiplier.toString())); 1503 } 1504 if (!status[STATUS_POSITIVE]) { 1505 bigDecimalResult = bigDecimalResult.negate(); 1506 } 1507 return bigDecimalResult; 1508 } else { 1509 Number cnfResult; 1510 if (digitList.fitsIntoLong(status[STATUS_POSITIVE], isParseIntegerOnly())) { 1511 long longResult = digitList.getLong(); 1512 cnfResult = generateParseResult(longResult, false, 1513 longResult < 0, status, cnfMultiplier); 1514 } else { 1515 cnfResult = generateParseResult(digitList.getDouble(), 1516 true, false, status, cnfMultiplier); 1517 } 1518 return cnfResult; 1519 } 1520 } 1521 1522 /** 1523 * Returns the parsed result by multiplying the parsed number 1524 * with the multiplier representing the prefix and suffix. 1525 * 1526 * @param number parsed number component 1527 * @param gotDouble whether the parsed number contains decimal 1528 * @param gotLongMin whether the parsed number is Long.MIN 1529 * @param status boolean status flags indicating whether the 1530 * value is infinite and whether it is positive 1531 * @param cnfMultiplier compact number multiplier 1532 * @return parsed result 1533 */ 1534 private Number generateParseResult(Number number, boolean gotDouble, 1535 boolean gotLongMin, boolean[] status, Number cnfMultiplier) { 1536 1537 if (gotDouble) { 1538 if (cnfMultiplier.longValue() != 1L) { 1539 double doubleResult = number.doubleValue() * cnfMultiplier.doubleValue(); 1540 doubleResult = (double) convertIfNegative(doubleResult, status, gotLongMin); 1541 // Check if a double can be represeneted as a long 1542 long longResult = (long) doubleResult; 1543 gotDouble = ((doubleResult != (double) longResult) 1544 || (doubleResult == 0.0 && 1 / doubleResult < 0.0)); 1545 return gotDouble ? (Number) doubleResult : (Number) longResult; 1546 } 1547 } else { 1548 if (cnfMultiplier.longValue() != 1L) { 1549 Number result; 1550 if ((cnfMultiplier instanceof Long) && !gotLongMin) { 1551 long longMultiplier = (long) cnfMultiplier; 1552 try { 1553 result = Math.multiplyExact(number.longValue(), 1554 longMultiplier); 1555 } catch (ArithmeticException ex) { 1556 // If number * longMultiplier can not be represented 1557 // as long return as double 1558 result = number.doubleValue() * cnfMultiplier.doubleValue(); 1559 } 1560 } else { 1561 // cnfMultiplier can not be stored into long or the number 1562 // part is Long.MIN, return as double 1563 result = number.doubleValue() * cnfMultiplier.doubleValue(); 1564 } 1565 return convertIfNegative(result, status, gotLongMin); 1566 } 1567 } 1568 1569 // Default number 1570 return convertIfNegative(number, status, gotLongMin); 1571 } 1572 1573 /** 1574 * Negate the parsed value if the positive status flag is false 1575 * and the value is not a Long.MIN 1576 * @param number parsed value 1577 * @param status boolean status flags indicating whether the 1578 * value is infinite and whether it is positive 1579 * @param gotLongMin whether the parsed number is Long.MIN 1580 * @return the resulting value 1581 */ 1582 private Number convertIfNegative(Number number, boolean[] status, 1583 boolean gotLongMin) { 1584 1585 if (!status[STATUS_POSITIVE] && !gotLongMin) { 1586 if (number instanceof Long) { 1587 return -(long) number; 1588 } else { 1589 return -(double) number; 1590 } 1591 } else { 1592 return number; 1593 } 1594 } 1595 1596 /** 1597 * Attempts to match the given {@code affix} in the 1598 * specified {@code text}. 1599 */ 1600 private boolean matchAffix(String text, int position, String affix, 1601 String defaultAffix, String matchedAffix) { 1602 1603 // Check with the compact affixes which are non empty and 1604 // do not match with default affix 1605 if (!affix.isEmpty() && !affix.equals(defaultAffix)) { 1606 // Look ahead only for the longer match than the previous match 1607 if (matchedAffix.length() < affix.length()) { 1608 if (text.regionMatches(position, affix, 0, affix.length())) { 1609 return true; 1610 } 1611 } 1612 } 1613 return false; 1614 } 1615 1616 /** 1617 * Attempts to match given {@code prefix} and {@code suffix} in 1618 * the specified {@code text}. 1619 */ 1620 private boolean matchPrefixAndSuffix(String text, int position, String prefix, 1621 String matchedPrefix, String defaultPrefix, String suffix, 1622 String matchedSuffix, String defaultSuffix) { 1623 1624 // Check the compact pattern suffix only if there is a 1625 // compact prefix match or a default prefix match 1626 // because the compact prefix and suffix should match at the same 1627 // index to obtain the multiplier. 1628 // The prefix match is required because of the possibility of 1629 // same prefix at multiple index, in which case matching the suffix 1630 // is used to obtain the single match 1631 1632 if (prefix.equals(matchedPrefix) 1633 || matchedPrefix.equals(defaultPrefix)) { 1634 return matchAffix(text, position, suffix, defaultSuffix, matchedSuffix); 1635 } 1636 return false; 1637 } 1638 1639 /** 1640 * Computes multiplier by matching the given {@code matchedPrefix} 1641 * and suffix in the specified {@code text} from the lists of 1642 * prefixes and suffixes extracted from compact patterns. 1643 * 1644 * @param text the string to parse 1645 * @param parsePosition the {@code ParsePosition} object representing the 1646 * index and error index of the parse string 1647 * @param matchedPrefix prefix extracted which needs to be matched to 1648 * obtain the multiplier 1649 * @param status upon return contains boolean status flags indicating 1650 * whether the value is positive 1651 * @param gotPositive based on the prefix parsed; whether the number is positive 1652 * @param gotNegative based on the prefix parsed; whether the number is negative 1653 * @return the multiplier matching the prefix and suffix; -1 otherwise 1654 */ 1655 private Number computeParseMultiplier(String text, ParsePosition parsePosition, 1656 String matchedPrefix, boolean[] status, boolean gotPositive, 1657 boolean gotNegative) { 1658 1659 int position = parsePosition.index; 1660 boolean gotPos = false; 1661 boolean gotNeg = false; 1662 int matchedPosIndex = -1; 1663 int matchedNegIndex = -1; 1664 String matchedPosSuffix = ""; 1665 String matchedNegSuffix = ""; 1666 for (int compactIndex = 0; compactIndex < compactPatterns.length; compactIndex++) { 1667 String positivePrefix = positivePrefixes.get(compactIndex); 1668 String negativePrefix = negativePrefixes.get(compactIndex); 1669 String positiveSuffix = positiveSuffixes.get(compactIndex); 1670 String negativeSuffix = negativeSuffixes.get(compactIndex); 1671 1672 // Do not break if a match occur; there is a possibility that the 1673 // subsequent affixes may match the longer subsequence in the given 1674 // string. 1675 // For example, matching "3Mdx" with "M", "Md" should match with "Md" 1676 boolean match = matchPrefixAndSuffix(text, position, positivePrefix, matchedPrefix, 1677 defaultDecimalFormat.getPositivePrefix(), positiveSuffix, 1678 matchedPosSuffix, defaultDecimalFormat.getPositiveSuffix()); 1679 if (match) { 1680 matchedPosIndex = compactIndex; 1681 matchedPosSuffix = positiveSuffix; 1682 gotPos = true; 1683 } 1684 1685 match = matchPrefixAndSuffix(text, position, negativePrefix, matchedPrefix, 1686 defaultDecimalFormat.getNegativePrefix(), negativeSuffix, 1687 matchedNegSuffix, defaultDecimalFormat.getNegativeSuffix()); 1688 if (match) { 1689 matchedNegIndex = compactIndex; 1690 matchedNegSuffix = negativeSuffix; 1691 gotNeg = true; 1692 } 1693 } 1694 1695 // Suffix in the given text does not match with the compact 1696 // patterns suffixes; match with the default suffix 1697 if (!gotPos && !gotNeg) { 1698 String positiveSuffix = defaultDecimalFormat.getPositiveSuffix(); 1699 String negativeSuffix = defaultDecimalFormat.getNegativeSuffix(); 1700 if (text.regionMatches(position, positiveSuffix, 0, 1701 positiveSuffix.length())) { 1702 // Matches the default positive prefix 1703 matchedPosSuffix = positiveSuffix; 1704 gotPos = true; 1705 } 1706 if (text.regionMatches(position, negativeSuffix, 0, 1707 negativeSuffix.length())) { 1708 // Matches the default negative suffix 1709 matchedNegSuffix = negativeSuffix; 1710 gotNeg = true; 1711 } 1712 } 1713 1714 // If both matches, take the longest one 1715 if (gotPos && gotNeg) { 1716 if (matchedPosSuffix.length() > matchedNegSuffix.length()) { 1717 gotNeg = false; 1718 } else if (matchedPosSuffix.length() < matchedNegSuffix.length()) { 1719 gotPos = false; 1720 } else { 1721 // If longest comparison fails; take the positive and negative 1722 // sign of matching prefix 1723 gotPos = gotPositive; 1724 gotNeg = gotNegative; 1725 } 1726 } 1727 1728 // Fail if neither or both 1729 if (gotPos == gotNeg) { 1730 parsePosition.errorIndex = position; 1731 return -1L; 1732 } 1733 1734 Number cnfMultiplier; 1735 // Update the parse position index and take compact multiplier 1736 // only if it matches the compact suffix, not the default 1737 // suffix; else multiplier should be 1 1738 if (gotPos) { 1739 parsePosition.index = position + matchedPosSuffix.length(); 1740 cnfMultiplier = matchedPosIndex != -1 1741 ? divisors.get(matchedPosIndex) : 1L; 1742 } else { 1743 parsePosition.index = position + matchedNegSuffix.length(); 1744 cnfMultiplier = matchedNegIndex != -1 1745 ? divisors.get(matchedNegIndex) : 1L; 1746 } 1747 status[STATUS_POSITIVE] = gotPos; 1748 return cnfMultiplier; 1749 } 1750 1751 /** 1752 * Reconstitutes this {@code CompactNumberFormat} from a stream 1753 * (that is, deserializes it) after performing some validations. 1754 * This method throws InvalidObjectException, if the stream data is invalid 1755 * because of the following reasons, 1756 * <ul> 1757 * <li> If any of the {@code decimalPattern}, {@code compactPatterns}, 1758 * {@code symbols} or {@code roundingMode} is {@code null}. 1759 * <li> If the {@code decimalPattern} or the {@code compactPatterns} array 1760 * contains an invalid pattern or if a {@code null} appears in the array of 1761 * compact patterns. 1762 * <li> If the {@code minimumIntegerDigits} is greater than the 1763 * {@code maximumIntegerDigits} or the {@code minimumFractionDigits} is 1764 * greater than the {@code maximumFractionDigits}. This check is performed 1765 * by superclass's Object. 1766 * <li> If any of the minimum/maximum integer/fraction digit count is 1767 * negative. This check is performed by superclass's readObject. 1768 * <li> If the minimum or maximum integer digit count is larger than 309 or 1769 * if the minimum or maximum fraction digit count is larger than 340. 1770 * <li> If the grouping size is negative or larger than 127. 1771 * </ul> 1772 * 1773 * @param inStream the stream 1774 * @throws IOException if an I/O error occurs 1775 * @throws ClassNotFoundException if the class of a serialized object 1776 * could not be found 1777 */ 1778 private void readObject(ObjectInputStream inStream) throws IOException, 1779 ClassNotFoundException { 1780 1781 inStream.defaultReadObject(); 1782 if (decimalPattern == null || compactPatterns == null 1783 || symbols == null || roundingMode == null) { 1784 throw new InvalidObjectException("One of the 'decimalPattern'," 1785 + " 'compactPatterns', 'symbols' or 'roundingMode'" 1786 + " is null"); 1787 } 1788 1789 // Check only the maximum counts because NumberFormat.readObject has 1790 // already ensured that the maximum is greater than the minimum count. 1791 if (getMaximumIntegerDigits() > DecimalFormat.DOUBLE_INTEGER_DIGITS 1792 || getMaximumFractionDigits() > DecimalFormat.DOUBLE_FRACTION_DIGITS) { 1793 throw new InvalidObjectException("Digit count out of range"); 1794 } 1795 1796 // Check if the grouping size is negative, on an attempt to 1797 // put value > 127, it wraps around, so check just negative value 1798 if (groupingSize < 0) { 1799 throw new InvalidObjectException("Grouping size is negative"); 1800 } 1801 1802 try { 1803 processCompactPatterns(); 1804 } catch (IllegalArgumentException ex) { 1805 throw new InvalidObjectException(ex.getMessage()); 1806 } 1807 1808 decimalFormat = new DecimalFormat(SPECIAL_PATTERN, symbols); 1809 decimalFormat.setMaximumFractionDigits(getMaximumFractionDigits()); 1810 decimalFormat.setMinimumFractionDigits(getMinimumFractionDigits()); 1811 decimalFormat.setMaximumIntegerDigits(getMaximumIntegerDigits()); 1812 decimalFormat.setMinimumIntegerDigits(getMinimumIntegerDigits()); 1813 decimalFormat.setRoundingMode(getRoundingMode()); 1814 decimalFormat.setGroupingSize(getGroupingSize()); 1815 decimalFormat.setGroupingUsed(isGroupingUsed()); 1816 decimalFormat.setParseIntegerOnly(isParseIntegerOnly()); 1817 1818 try { 1819 defaultDecimalFormat = new DecimalFormat(decimalPattern, symbols); 1820 defaultDecimalFormat.setMaximumFractionDigits(0); 1821 } catch (IllegalArgumentException ex) { 1822 throw new InvalidObjectException(ex.getMessage()); 1823 } 1824 1825 } 1826 1827 /** 1828 * Sets the maximum number of digits allowed in the integer portion of a 1829 * number. 1830 * The maximum allowed integer range is 309, if the {@code newValue} > 309, 1831 * then the maximum integer digits count is set to 309. Negative input 1832 * values are replaced with 0. 1833 * 1834 * @param newValue the maximum number of integer digits to be shown 1835 * @see #getMaximumIntegerDigits() 1836 */ 1837 @Override 1838 public void setMaximumIntegerDigits(int newValue) { 1839 // The maximum integer digits is checked with the allowed range before calling 1840 // the DecimalFormat.setMaximumIntegerDigits, which performs the negative check 1841 // on the given newValue while setting it as max integer digits. 1842 // For example, if a negative value is specified, it is replaced with 0 1843 decimalFormat.setMaximumIntegerDigits(Math.min(newValue, 1844 DecimalFormat.DOUBLE_INTEGER_DIGITS)); 1845 super.setMaximumIntegerDigits(decimalFormat.getMaximumIntegerDigits()); 1846 if (decimalFormat.getMinimumIntegerDigits() > decimalFormat.getMaximumIntegerDigits()) { 1847 decimalFormat.setMinimumIntegerDigits(decimalFormat.getMaximumIntegerDigits()); 1848 super.setMinimumIntegerDigits(decimalFormat.getMinimumIntegerDigits()); 1849 } 1850 } 1851 1852 /** 1853 * Sets the minimum number of digits allowed in the integer portion of a 1854 * number. 1855 * The maximum allowed integer range is 309, if the {@code newValue} > 309, 1856 * then the minimum integer digits count is set to 309. Negative input 1857 * values are replaced with 0. 1858 * 1859 * @param newValue the minimum number of integer digits to be shown 1860 * @see #getMinimumIntegerDigits() 1861 */ 1862 @Override 1863 public void setMinimumIntegerDigits(int newValue) { 1864 // The minimum integer digits is checked with the allowed range before calling 1865 // the DecimalFormat.setMinimumIntegerDigits, which performs check on the given 1866 // newValue while setting it as min integer digits. For example, if a negative 1867 // value is specified, it is replaced with 0 1868 decimalFormat.setMinimumIntegerDigits(Math.min(newValue, 1869 DecimalFormat.DOUBLE_INTEGER_DIGITS)); 1870 super.setMinimumIntegerDigits(decimalFormat.getMinimumIntegerDigits()); 1871 if (decimalFormat.getMinimumIntegerDigits() > decimalFormat.getMaximumIntegerDigits()) { 1872 decimalFormat.setMaximumIntegerDigits(decimalFormat.getMinimumIntegerDigits()); 1873 super.setMaximumIntegerDigits(decimalFormat.getMaximumIntegerDigits()); 1874 } 1875 } 1876 1877 /** 1878 * Sets the minimum number of digits allowed in the fraction portion of a 1879 * number. 1880 * The maximum allowed fraction range is 340, if the {@code newValue} > 340, 1881 * then the minimum fraction digits count is set to 340. Negative input 1882 * values are replaced with 0. 1883 * 1884 * @param newValue the minimum number of fraction digits to be shown 1885 * @see #getMinimumFractionDigits() 1886 */ 1887 @Override 1888 public void setMinimumFractionDigits(int newValue) { 1889 // The minimum fraction digits is checked with the allowed range before 1890 // calling the DecimalFormat.setMinimumFractionDigits, which performs 1891 // check on the given newValue while setting it as min fraction 1892 // digits. For example, if a negative value is specified, it is 1893 // replaced with 0 1894 decimalFormat.setMinimumFractionDigits(Math.min(newValue, 1895 DecimalFormat.DOUBLE_FRACTION_DIGITS)); 1896 super.setMinimumFractionDigits(decimalFormat.getMinimumFractionDigits()); 1897 if (decimalFormat.getMinimumFractionDigits() > decimalFormat.getMaximumFractionDigits()) { 1898 decimalFormat.setMaximumFractionDigits(decimalFormat.getMinimumFractionDigits()); 1899 super.setMaximumFractionDigits(decimalFormat.getMaximumFractionDigits()); 1900 } 1901 } 1902 1903 /** 1904 * Sets the maximum number of digits allowed in the fraction portion of a 1905 * number. 1906 * The maximum allowed fraction range is 340, if the {@code newValue} > 340, 1907 * then the maximum fraction digits count is set to 340. Negative input 1908 * values are replaced with 0. 1909 * 1910 * @param newValue the maximum number of fraction digits to be shown 1911 * @see #getMaximumFractionDigits() 1912 */ 1913 @Override 1914 public void setMaximumFractionDigits(int newValue) { 1915 // The maximum fraction digits is checked with the allowed range before 1916 // calling the DecimalFormat.setMaximumFractionDigits, which performs 1917 // check on the given newValue while setting it as max fraction digits. 1918 // For example, if a negative value is specified, it is replaced with 0 1919 decimalFormat.setMaximumFractionDigits(Math.min(newValue, 1920 DecimalFormat.DOUBLE_FRACTION_DIGITS)); 1921 super.setMaximumFractionDigits(decimalFormat.getMaximumFractionDigits()); 1922 if (decimalFormat.getMinimumFractionDigits() > decimalFormat.getMaximumFractionDigits()) { 1923 decimalFormat.setMinimumFractionDigits(decimalFormat.getMaximumFractionDigits()); 1924 super.setMinimumFractionDigits(decimalFormat.getMinimumFractionDigits()); 1925 } 1926 } 1927 1928 /** 1929 * Gets the {@link java.math.RoundingMode} used in this 1930 * {@code CompactNumberFormat}. 1931 * 1932 * @return the {@code RoundingMode} used for this 1933 * {@code CompactNumberFormat} 1934 * @see #setRoundingMode(RoundingMode) 1935 */ 1936 @Override 1937 public RoundingMode getRoundingMode() { 1938 return roundingMode; 1939 } 1940 1941 /** 1942 * Sets the {@link java.math.RoundingMode} used in this 1943 * {@code CompactNumberFormat}. 1944 * 1945 * @param roundingMode the {@code RoundingMode} to be used 1946 * @see #getRoundingMode() 1947 * @throws NullPointerException if {@code roundingMode} is {@code null} 1948 */ 1949 @Override 1950 public void setRoundingMode(RoundingMode roundingMode) { 1951 decimalFormat.setRoundingMode(roundingMode); 1952 this.roundingMode = roundingMode; 1953 } 1954 1955 /** 1956 * Returns the grouping size. Grouping size is the number of digits between 1957 * grouping separators in the integer portion of a number. For example, 1958 * in the compact number {@code "12,347 trillion"} for the 1959 * {@link java.util.Locale#US US locale}, the grouping size is 3. 1960 * 1961 * @return the grouping size 1962 * @see #setGroupingSize 1963 * @see java.text.NumberFormat#isGroupingUsed 1964 * @see java.text.DecimalFormatSymbols#getGroupingSeparator 1965 */ 1966 public int getGroupingSize() { 1967 return groupingSize; 1968 } 1969 1970 /** 1971 * Sets the grouping size. Grouping size is the number of digits between 1972 * grouping separators in the integer portion of a number. For example, 1973 * in the compact number {@code "12,347 trillion"} for the 1974 * {@link java.util.Locale#US US locale}, the grouping size is 3. The grouping 1975 * size must be greater than or equal to zero and less than or equal to 127. 1976 * 1977 * @param newValue the new grouping size 1978 * @see #getGroupingSize 1979 * @see java.text.NumberFormat#setGroupingUsed 1980 * @see java.text.DecimalFormatSymbols#setGroupingSeparator 1981 * @throws IllegalArgumentException if {@code newValue} is negative or 1982 * larger than 127 1983 */ 1984 public void setGroupingSize(int newValue) { 1985 if (newValue < 0 || newValue > 127) { 1986 throw new IllegalArgumentException( 1987 "The value passed is negative or larger than 127"); 1988 } 1989 groupingSize = (byte) newValue; 1990 decimalFormat.setGroupingSize(groupingSize); 1991 } 1992 1993 /** 1994 * Returns true if grouping is used in this format. For example, with 1995 * grouping on and grouping size set to 3, the number {@code 12346567890987654} 1996 * can be formatted as {@code "12,347 trillion"} in the 1997 * {@link java.util.Locale#US US locale}. 1998 * The grouping separator is locale dependent. 1999 * 2000 * @return {@code true} if grouping is used; 2001 * {@code false} otherwise 2002 * @see #setGroupingUsed 2003 */ 2004 @Override 2005 public boolean isGroupingUsed() { 2006 return super.isGroupingUsed(); 2007 } 2008 2009 /** 2010 * Sets whether or not grouping will be used in this format. 2011 * 2012 * @param newValue {@code true} if grouping is used; 2013 * {@code false} otherwise 2014 * @see #isGroupingUsed 2015 */ 2016 @Override 2017 public void setGroupingUsed(boolean newValue) { 2018 decimalFormat.setGroupingUsed(newValue); 2019 super.setGroupingUsed(newValue); 2020 } 2021 2022 /** 2023 * Returns true if this format parses only an integer from the number 2024 * component of a compact number. 2025 * Parsing an integer means that only an integer is considered from the 2026 * number component, prefix/suffix is still considered to compute the 2027 * resulting output. 2028 * For example, in the {@link java.util.Locale#US US locale}, if this method 2029 * returns {@code true}, the string {@code "1234.78 thousand"} would be 2030 * parsed as the value {@code 1234000} (1234 (integer part) * 1000 2031 * (thousand)) and the fractional part would be skipped. 2032 * The exact format accepted by the parse operation is locale dependent. 2033 * 2034 * @return {@code true} if compact numbers should be parsed as integers 2035 * only; {@code false} otherwise 2036 */ 2037 @Override 2038 public boolean isParseIntegerOnly() { 2039 return super.isParseIntegerOnly(); 2040 } 2041 2042 /** 2043 * Sets whether or not this format parses only an integer from the number 2044 * component of a compact number. 2045 * 2046 * @param value {@code true} if compact numbers should be parsed as 2047 * integers only; {@code false} otherwise 2048 * @see #isParseIntegerOnly 2049 */ 2050 @Override 2051 public void setParseIntegerOnly(boolean value) { 2052 decimalFormat.setParseIntegerOnly(value); 2053 super.setParseIntegerOnly(value); 2054 } 2055 2056 /** 2057 * Returns whether the {@link #parse(String, ParsePosition)} 2058 * method returns {@code BigDecimal}. The default value is false. 2059 * 2060 * @return {@code true} if the parse method returns BigDecimal; 2061 * {@code false} otherwise 2062 * @see #setParseBigDecimal 2063 * 2064 */ 2065 public boolean isParseBigDecimal() { 2066 return parseBigDecimal; 2067 } 2068 2069 /** 2070 * Sets whether the {@link #parse(String, ParsePosition)} 2071 * method returns {@code BigDecimal}. 2072 * 2073 * @param newValue {@code true} if the parse method returns BigDecimal; 2074 * {@code false} otherwise 2075 * @see #isParseBigDecimal 2076 * 2077 */ 2078 public void setParseBigDecimal(boolean newValue) { 2079 parseBigDecimal = newValue; 2080 } 2081 2082 /** 2083 * Checks if this {@code CompactNumberFormat} is equal to the 2084 * specified {@code obj}. The objects of type {@code CompactNumberFormat} 2085 * are compared, other types return false; obeys the general contract of 2086 * {@link java.lang.Object#equals(java.lang.Object) Object.equals}. 2087 * 2088 * @param obj the object to compare with 2089 * @return true if this is equal to the other {@code CompactNumberFormat} 2090 */ 2091 @Override 2092 public boolean equals(Object obj) { 2093 2094 if (!super.equals(obj)) { 2095 return false; 2096 } 2097 2098 CompactNumberFormat other = (CompactNumberFormat) obj; 2099 return decimalPattern.equals(other.decimalPattern) 2100 && symbols.equals(other.symbols) 2101 && Arrays.equals(compactPatterns, other.compactPatterns) 2102 && roundingMode.equals(other.roundingMode) 2103 && groupingSize == other.groupingSize 2104 && parseBigDecimal == other.parseBigDecimal; 2105 } 2106 2107 /** 2108 * Returns the hash code for this {@code CompactNumberFormat} instance. 2109 * 2110 * @return hash code for this {@code CompactNumberFormat} 2111 */ 2112 @Override 2113 public int hashCode() { 2114 return 31 * super.hashCode() + 2115 Objects.hash(decimalPattern, symbols, roundingMode) 2116 + Arrays.hashCode(compactPatterns) + groupingSize 2117 + Boolean.hashCode(parseBigDecimal); 2118 } 2119 2120 /** 2121 * Creates and returns a copy of this {@code CompactNumberFormat} 2122 * instance. 2123 * 2124 * @return a clone of this instance 2125 */ 2126 @Override 2127 public CompactNumberFormat clone() { 2128 CompactNumberFormat other = (CompactNumberFormat) super.clone(); 2129 other.compactPatterns = compactPatterns.clone(); 2130 other.symbols = (DecimalFormatSymbols) symbols.clone(); 2131 return other; 2132 } 2133 2134 } 2135