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