1 /* 2 * Copyright (c) 1996, 2017, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 /* 27 * (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved 28 * (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved 29 * 30 * The original version of this source code and documentation is copyrighted 31 * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These 32 * materials are provided under terms of a License Agreement between Taligent 33 * and Sun. This technology is protected by multiple US and International 34 * patents. This notice and attribution to Taligent may not be removed. 35 * Taligent is a registered trademark of Taligent, Inc. 36 * 37 */ 38 39 package java.text; 40 41 import java.io.InvalidObjectException; 42 import java.io.IOException; 43 import java.io.ObjectInputStream; 44 import java.io.ObjectOutputStream; 45 import java.math.BigInteger; 46 import java.math.RoundingMode; 47 import java.text.spi.NumberFormatProvider; 48 import java.util.Currency; 49 import java.util.HashMap; 50 import java.util.Hashtable; 51 import java.util.Locale; 52 import java.util.Map; 53 import java.util.ResourceBundle; 54 import java.util.concurrent.atomic.AtomicInteger; 55 import java.util.concurrent.atomic.AtomicLong; 56 import java.util.spi.LocaleServiceProvider; 57 import sun.util.locale.provider.LocaleProviderAdapter; 58 import sun.util.locale.provider.LocaleServiceProviderPool; 59 60 /** 61 * <code>NumberFormat</code> is the abstract base class for all number 62 * formats. This class provides the interface for formatting and parsing 63 * numbers. <code>NumberFormat</code> also provides methods for determining 64 * which locales have number formats, and what their names are. 65 * 66 * <p> 67 * <code>NumberFormat</code> helps you to format and parse numbers for any locale. 68 * Your code can be completely independent of the locale conventions for 69 * decimal points, thousands-separators, or even the particular decimal 70 * digits used, or whether the number format is even decimal. 71 * 72 * <p> 73 * To format a number for the current Locale, use one of the factory 74 * class methods: 75 * <blockquote> 76 * <pre>{@code 77 * myString = NumberFormat.getInstance().format(myNumber); 78 * }</pre> 79 * </blockquote> 80 * If you are formatting multiple numbers, it is 81 * more efficient to get the format and use it multiple times so that 82 * the system doesn't have to fetch the information about the local 83 * language and country conventions multiple times. 84 * <blockquote> 85 * <pre>{@code 86 * NumberFormat nf = NumberFormat.getInstance(); 87 * for (int i = 0; i < myNumber.length; ++i) { 88 * output.println(nf.format(myNumber[i]) + "; "); 89 * } 90 * }</pre> 91 * </blockquote> 92 * To format a number for a different Locale, specify it in the 93 * call to <code>getInstance</code>. 94 * <blockquote> 95 * <pre>{@code 96 * NumberFormat nf = NumberFormat.getInstance(Locale.FRENCH); 97 * }</pre> 98 * </blockquote> 99 * You can also use a <code>NumberFormat</code> to parse numbers: 100 * <blockquote> 101 * <pre>{@code 102 * myNumber = nf.parse(myString); 103 * }</pre> 104 * </blockquote> 105 * Use <code>getInstance</code> or <code>getNumberInstance</code> to get the 106 * normal number format. Use <code>getIntegerInstance</code> to get an 107 * integer number format. Use <code>getCurrencyInstance</code> to get the 108 * currency number format. And use <code>getPercentInstance</code> to get a 109 * format for displaying percentages. With this format, a fraction like 110 * 0.53 is displayed as 53%. 111 * 112 * <p> 113 * You can also control the display of numbers with such methods as 114 * <code>setMinimumFractionDigits</code>. 115 * If you want even more control over the format or parsing, 116 * or want to give your users more control, 117 * you can try casting the <code>NumberFormat</code> you get from the factory methods 118 * to a <code>DecimalFormat</code>. This will work for the vast majority 119 * of locales; just remember to put it in a <code>try</code> block in case you 120 * encounter an unusual one. 121 * 122 * <p> 123 * NumberFormat and DecimalFormat are designed such that some controls 124 * work for formatting and others work for parsing. The following is 125 * the detailed description for each these control methods, 126 * <p> 127 * setParseIntegerOnly : only affects parsing, e.g. 128 * if true, "3456.78" → 3456 (and leaves the parse position just after index 6) 129 * if false, "3456.78" → 3456.78 (and leaves the parse position just after index 8) 130 * This is independent of formatting. If you want to not show a decimal point 131 * where there might be no digits after the decimal point, use 132 * setDecimalSeparatorAlwaysShown. 133 * <p> 134 * setDecimalSeparatorAlwaysShown : only affects formatting, and only where 135 * there might be no digits after the decimal point, such as with a pattern 136 * like "#,##0.##", e.g., 137 * if true, 3456.00 → "3,456." 138 * if false, 3456.00 → "3456" 139 * This is independent of parsing. If you want parsing to stop at the decimal 140 * point, use setParseIntegerOnly. 141 * 142 * <p> 143 * You can also use forms of the <code>parse</code> and <code>format</code> 144 * methods with <code>ParsePosition</code> and <code>FieldPosition</code> to 145 * allow you to: 146 * <ul> 147 * <li> progressively parse through pieces of a string 148 * <li> align the decimal point and other areas 149 * </ul> 150 * For example, you can align numbers in two ways: 151 * <ol> 152 * <li> If you are using a monospaced font with spacing for alignment, 153 * you can pass the <code>FieldPosition</code> in your format call, with 154 * <code>field</code> = <code>INTEGER_FIELD</code>. On output, 155 * <code>getEndIndex</code> will be set to the offset between the 156 * last character of the integer and the decimal. Add 157 * (desiredSpaceCount - getEndIndex) spaces at the front of the string. 158 * 159 * <li> If you are using proportional fonts, 160 * instead of padding with spaces, measure the width 161 * of the string in pixels from the start to <code>getEndIndex</code>. 162 * Then move the pen by 163 * (desiredPixelWidth - widthToAlignmentPoint) before drawing the text. 164 * It also works where there is no decimal, but possibly additional 165 * characters at the end, e.g., with parentheses in negative 166 * numbers: "(12)" for -12. 167 * </ol> 168 * 169 * <h3><a id="synchronization">Synchronization</a></h3> 170 * 171 * <p> 172 * Number formats are generally not synchronized. 173 * It is recommended to create separate format instances for each thread. 174 * If multiple threads access a format concurrently, it must be synchronized 175 * externally. 176 * 177 * @implSpec The {@link #format(double, StringBuffer, FieldPosition)}, 178 * {@link #format(long, StringBuffer, FieldPosition)} and 179 * {@link #parse(String, ParsePosition)} methods may throw 180 * {@code NullPointerException}, if any of their parameter is {@code null}. 181 * The subclass may provide its own implementation and specification about 182 * {@code NullPointerException}. 183 * 184 * @implSpec 185 * <p> 186 * {@code NumberFormat} provides rounding modes defined 187 * in {@link java.math.RoundingMode} for formatting numbers. By default, 188 * it uses the {@linkplain java.math.RoundingMode#HALF_EVEN 189 * round half-even algorithm}. To change the rounding mode use 190 * {@link #setRoundingMode(java.math.RoundingMode) setRoundingMode}. 191 * The {@code NumberFormat} returned by the static factory methods is 192 * configured to round floating point numbers using half-even 193 * rounding (see {@link java.math.RoundingMode#HALF_EVEN 194 * RoundingMode.HALF_EVEN}) for formatting. 195 * 196 * @see DecimalFormat 197 * @see ChoiceFormat 198 * @author Mark Davis 199 * @author Helena Shih 200 * @since 1.1 201 */ 202 public abstract class NumberFormat extends Format { 203 204 /** 205 * Field constant used to construct a FieldPosition object. Signifies that 206 * the position of the integer part of a formatted number should be returned. 207 * @see java.text.FieldPosition 208 */ 209 public static final int INTEGER_FIELD = 0; 210 211 /** 212 * Field constant used to construct a FieldPosition object. Signifies that 213 * the position of the fraction part of a formatted number should be returned. 214 * @see java.text.FieldPosition 215 */ 216 public static final int FRACTION_FIELD = 1; 217 218 /** 219 * Sole constructor. (For invocation by subclass constructors, typically 220 * implicit.) 221 */ 222 protected NumberFormat() { 223 } 224 225 /** 226 * Formats a number and appends the resulting text to the given string 227 * buffer. 228 * The number can be of any subclass of {@link java.lang.Number}. 229 * <p> 230 * This implementation extracts the number's value using 231 * {@link java.lang.Number#longValue()} for all integral type values that 232 * can be converted to <code>long</code> without loss of information, 233 * including <code>BigInteger</code> values with a 234 * {@link java.math.BigInteger#bitLength() bit length} of less than 64, 235 * and {@link java.lang.Number#doubleValue()} for all other types. It 236 * then calls 237 * {@link #format(long,java.lang.StringBuffer,java.text.FieldPosition)} 238 * or {@link #format(double,java.lang.StringBuffer,java.text.FieldPosition)}. 239 * This may result in loss of magnitude information and precision for 240 * <code>BigInteger</code> and <code>BigDecimal</code> values. 241 * @param number the number to format 242 * @param toAppendTo the <code>StringBuffer</code> to which the formatted 243 * text is to be appended 244 * @param pos On input: an alignment field, if desired. 245 * On output: the offsets of the alignment field. 246 * @return the value passed in as <code>toAppendTo</code> 247 * @exception IllegalArgumentException if <code>number</code> is 248 * null or not an instance of <code>Number</code>. 249 * @exception NullPointerException if <code>toAppendTo</code> or 250 * <code>pos</code> is null 251 * @exception ArithmeticException if rounding is needed with rounding 252 * mode being set to RoundingMode.UNNECESSARY 253 * @see java.text.FieldPosition 254 */ 255 @Override 256 public StringBuffer format(Object number, 257 StringBuffer toAppendTo, 258 FieldPosition pos) { 259 if (number instanceof Long || number instanceof Integer || 260 number instanceof Short || number instanceof Byte || 261 number instanceof AtomicInteger || number instanceof AtomicLong || 262 (number instanceof BigInteger && 263 ((BigInteger)number).bitLength() < 64)) { 264 return format(((Number)number).longValue(), toAppendTo, pos); 265 } else if (number instanceof Number) { 266 return format(((Number)number).doubleValue(), toAppendTo, pos); 267 } else { 268 throw new IllegalArgumentException("Cannot format given Object as a Number"); 269 } 270 } 271 272 /** 273 * Parses text from a string to produce a <code>Number</code>. 274 * <p> 275 * The method attempts to parse text starting at the index given by 276 * <code>pos</code>. 277 * If parsing succeeds, then the index of <code>pos</code> is updated 278 * to the index after the last character used (parsing does not necessarily 279 * use all characters up to the end of the string), and the parsed 280 * number is returned. The updated <code>pos</code> can be used to 281 * indicate the starting point for the next call to this method. 282 * If an error occurs, then the index of <code>pos</code> is not 283 * changed, the error index of <code>pos</code> is set to the index of 284 * the character where the error occurred, and null is returned. 285 * <p> 286 * See the {@link #parse(String, ParsePosition)} method for more information 287 * on number parsing. 288 * 289 * @param source A <code>String</code>, part of which should be parsed. 290 * @param pos A <code>ParsePosition</code> object with index and error 291 * index information as described above. 292 * @return A <code>Number</code> parsed from the string. In case of 293 * error, returns null. 294 * @throws NullPointerException if {@code source} or {@code pos} is null. 295 */ 296 @Override 297 public final Object parseObject(String source, ParsePosition pos) { 298 return parse(source, pos); 299 } 300 301 /** 302 * Specialization of format. 303 * 304 * @param number the double number to format 305 * @return the formatted String 306 * @exception ArithmeticException if rounding is needed with rounding 307 * mode being set to RoundingMode.UNNECESSARY 308 * @see java.text.Format#format 309 */ 310 public final String format(double number) { 311 // Use fast-path for double result if that works 312 String result = fastFormat(number); 313 if (result != null) 314 return result; 315 316 return format(number, new StringBuffer(), 317 DontCareFieldPosition.INSTANCE).toString(); 318 } 319 320 /* 321 * fastFormat() is supposed to be implemented in concrete subclasses only. 322 * Default implem always returns null. 323 */ 324 String fastFormat(double number) { return null; } 325 326 /** 327 * Specialization of format. 328 * 329 * @param number the long number to format 330 * @return the formatted String 331 * @exception ArithmeticException if rounding is needed with rounding 332 * mode being set to RoundingMode.UNNECESSARY 333 * @see java.text.Format#format 334 */ 335 public final String format(long number) { 336 return format(number, new StringBuffer(), 337 DontCareFieldPosition.INSTANCE).toString(); 338 } 339 340 /** 341 * Specialization of format. 342 * 343 * @param number the double number to format 344 * @param toAppendTo the StringBuffer to which the formatted text is to be 345 * appended 346 * @param pos the field position 347 * @return the formatted StringBuffer 348 * @exception ArithmeticException if rounding is needed with rounding 349 * mode being set to RoundingMode.UNNECESSARY 350 * @see java.text.Format#format 351 */ 352 public abstract StringBuffer format(double number, 353 StringBuffer toAppendTo, 354 FieldPosition pos); 355 356 /** 357 * Specialization of format. 358 * 359 * @param number the long number to format 360 * @param toAppendTo the StringBuffer to which the formatted text is to be 361 * appended 362 * @param pos the field position 363 * @return the formatted StringBuffer 364 * @exception ArithmeticException if rounding is needed with rounding 365 * mode being set to RoundingMode.UNNECESSARY 366 * @see java.text.Format#format 367 */ 368 public abstract StringBuffer format(long number, 369 StringBuffer toAppendTo, 370 FieldPosition pos); 371 372 /** 373 * Returns a Long if possible (e.g., within the range [Long.MIN_VALUE, 374 * Long.MAX_VALUE] and with no decimals), otherwise a Double. 375 * If IntegerOnly is set, will stop at a decimal 376 * point (or equivalent; e.g., for rational numbers "1 2/3", will stop 377 * after the 1). 378 * Does not throw an exception; if no object can be parsed, index is 379 * unchanged! 380 * 381 * @param source the String to parse 382 * @param parsePosition the parse position 383 * @return the parsed value 384 * @see java.text.NumberFormat#isParseIntegerOnly 385 * @see java.text.Format#parseObject 386 */ 387 public abstract Number parse(String source, ParsePosition parsePosition); 388 389 /** 390 * Parses text from the beginning of the given string to produce a number. 391 * The method may not use the entire text of the given string. 392 * <p> 393 * See the {@link #parse(String, ParsePosition)} method for more information 394 * on number parsing. 395 * 396 * @param source A <code>String</code> whose beginning should be parsed. 397 * @return A <code>Number</code> parsed from the string. 398 * @exception ParseException if the beginning of the specified string 399 * cannot be parsed. 400 */ 401 public Number parse(String source) throws ParseException { 402 ParsePosition parsePosition = new ParsePosition(0); 403 Number result = parse(source, parsePosition); 404 if (parsePosition.index == 0) { 405 throw new ParseException("Unparseable number: \"" + source + "\"", 406 parsePosition.errorIndex); 407 } 408 return result; 409 } 410 411 /** 412 * Returns true if this format will parse numbers as integers only. 413 * For example in the English locale, with ParseIntegerOnly true, the 414 * string "1234." would be parsed as the integer value 1234 and parsing 415 * would stop at the "." character. Of course, the exact format accepted 416 * by the parse operation is locale dependant and determined by sub-classes 417 * of NumberFormat. 418 * 419 * @return {@code true} if numbers should be parsed as integers only; 420 * {@code false} otherwise 421 */ 422 public boolean isParseIntegerOnly() { 423 return parseIntegerOnly; 424 } 425 426 /** 427 * Sets whether or not numbers should be parsed as integers only. 428 * 429 * @param value {@code true} if numbers should be parsed as integers only; 430 * {@code false} otherwise 431 * @see #isParseIntegerOnly 432 */ 433 public void setParseIntegerOnly(boolean value) { 434 parseIntegerOnly = value; 435 } 436 437 //============== Locale Stuff ===================== 438 439 /** 440 * Returns a general-purpose number format for the current default 441 * {@link java.util.Locale.Category#FORMAT FORMAT} locale. 442 * This is the same as calling 443 * {@link #getNumberInstance() getNumberInstance()}. 444 * 445 * @return the {@code NumberFormat} instance for general-purpose number 446 * formatting 447 */ 448 public static final NumberFormat getInstance() { 449 return getInstance(Locale.getDefault(Locale.Category.FORMAT), NUMBERSTYLE); 450 } 451 452 /** 453 * Returns a general-purpose number format for the specified locale. 454 * This is the same as calling 455 * {@link #getNumberInstance(java.util.Locale) getNumberInstance(inLocale)}. 456 * 457 * @param inLocale the desired locale 458 * @return the {@code NumberFormat} instance for general-purpose number 459 * formatting 460 */ 461 public static NumberFormat getInstance(Locale inLocale) { 462 return getInstance(inLocale, NUMBERSTYLE); 463 } 464 465 /** 466 * Returns a general-purpose number format for the current default 467 * {@link java.util.Locale.Category#FORMAT FORMAT} locale. 468 * <p>This is equivalent to calling 469 * {@link #getNumberInstance(Locale) 470 * getNumberInstance(Locale.getDefault(Locale.Category.FORMAT))}. 471 * 472 * @return the {@code NumberFormat} instance for general-purpose number 473 * formatting 474 * @see java.util.Locale#getDefault(java.util.Locale.Category) 475 * @see java.util.Locale.Category#FORMAT 476 */ 477 public static final NumberFormat getNumberInstance() { 478 return getInstance(Locale.getDefault(Locale.Category.FORMAT), NUMBERSTYLE); 479 } 480 481 /** 482 * Returns a general-purpose number format for the specified locale. 483 * 484 * @param inLocale the desired locale 485 * @return the {@code NumberFormat} instance for general-purpose number 486 * formatting 487 */ 488 public static NumberFormat getNumberInstance(Locale inLocale) { 489 return getInstance(inLocale, NUMBERSTYLE); 490 } 491 492 /** 493 * Returns an integer number format for the current default 494 * {@link java.util.Locale.Category#FORMAT FORMAT} locale. The 495 * returned number format is configured to round floating point numbers 496 * to the nearest integer using half-even rounding (see {@link 497 * java.math.RoundingMode#HALF_EVEN RoundingMode.HALF_EVEN}) for formatting, 498 * and to parse only the integer part of an input string (see {@link 499 * #isParseIntegerOnly isParseIntegerOnly}). 500 * <p>This is equivalent to calling 501 * {@link #getIntegerInstance(Locale) 502 * getIntegerInstance(Locale.getDefault(Locale.Category.FORMAT))}. 503 * 504 * @see #getRoundingMode() 505 * @see java.util.Locale#getDefault(java.util.Locale.Category) 506 * @see java.util.Locale.Category#FORMAT 507 * @return a number format for integer values 508 * @since 1.4 509 */ 510 public static final NumberFormat getIntegerInstance() { 511 return getInstance(Locale.getDefault(Locale.Category.FORMAT), INTEGERSTYLE); 512 } 513 514 /** 515 * Returns an integer number format for the specified locale. The 516 * returned number format is configured to round floating point numbers 517 * to the nearest integer using half-even rounding (see {@link 518 * java.math.RoundingMode#HALF_EVEN RoundingMode.HALF_EVEN}) for formatting, 519 * and to parse only the integer part of an input string (see {@link 520 * #isParseIntegerOnly isParseIntegerOnly}). 521 * 522 * @param inLocale the desired locale 523 * @see #getRoundingMode() 524 * @return a number format for integer values 525 * @since 1.4 526 */ 527 public static NumberFormat getIntegerInstance(Locale inLocale) { 528 return getInstance(inLocale, INTEGERSTYLE); 529 } 530 531 /** 532 * Returns a currency format for the current default 533 * {@link java.util.Locale.Category#FORMAT FORMAT} locale. 534 * <p>This is equivalent to calling 535 * {@link #getCurrencyInstance(Locale) 536 * getCurrencyInstance(Locale.getDefault(Locale.Category.FORMAT))}. 537 * 538 * @return the {@code NumberFormat} instance for currency formatting 539 * @see java.util.Locale#getDefault(java.util.Locale.Category) 540 * @see java.util.Locale.Category#FORMAT 541 */ 542 public static final NumberFormat getCurrencyInstance() { 543 return getInstance(Locale.getDefault(Locale.Category.FORMAT), CURRENCYSTYLE); 544 } 545 546 /** 547 * Returns a currency format for the specified locale. 548 * 549 * @param inLocale the desired locale 550 * @return the {@code NumberFormat} instance for currency formatting 551 */ 552 public static NumberFormat getCurrencyInstance(Locale inLocale) { 553 return getInstance(inLocale, CURRENCYSTYLE); 554 } 555 556 /** 557 * Returns a percentage format for the current default 558 * {@link java.util.Locale.Category#FORMAT FORMAT} locale. 559 * <p>This is equivalent to calling 560 * {@link #getPercentInstance(Locale) 561 * getPercentInstance(Locale.getDefault(Locale.Category.FORMAT))}. 562 * 563 * @return the {@code NumberFormat} instance for percentage formatting 564 * @see java.util.Locale#getDefault(java.util.Locale.Category) 565 * @see java.util.Locale.Category#FORMAT 566 */ 567 public static final NumberFormat getPercentInstance() { 568 return getInstance(Locale.getDefault(Locale.Category.FORMAT), PERCENTSTYLE); 569 } 570 571 /** 572 * Returns a percentage format for the specified locale. 573 * 574 * @param inLocale the desired locale 575 * @return the {@code NumberFormat} instance for percentage formatting 576 */ 577 public static NumberFormat getPercentInstance(Locale inLocale) { 578 return getInstance(inLocale, PERCENTSTYLE); 579 } 580 581 /** 582 * Returns a scientific format for the current default locale. 583 */ 584 /*public*/ final static NumberFormat getScientificInstance() { 585 return getInstance(Locale.getDefault(Locale.Category.FORMAT), SCIENTIFICSTYLE); 586 } 587 588 /** 589 * Returns a scientific format for the specified locale. 590 * 591 * @param inLocale the desired locale 592 */ 593 /*public*/ static NumberFormat getScientificInstance(Locale inLocale) { 594 return getInstance(inLocale, SCIENTIFICSTYLE); 595 } 596 597 /** 598 * Returns an array of all locales for which the 599 * <code>get*Instance</code> methods of this class can return 600 * localized instances. 601 * The returned array represents the union of locales supported by the Java 602 * runtime and by installed 603 * {@link java.text.spi.NumberFormatProvider NumberFormatProvider} implementations. 604 * It must contain at least a <code>Locale</code> instance equal to 605 * {@link java.util.Locale#US Locale.US}. 606 * 607 * @return An array of locales for which localized 608 * <code>NumberFormat</code> instances are available. 609 */ 610 public static Locale[] getAvailableLocales() { 611 LocaleServiceProviderPool pool = 612 LocaleServiceProviderPool.getPool(NumberFormatProvider.class); 613 return pool.getAvailableLocales(); 614 } 615 616 /** 617 * Overrides hashCode. 618 */ 619 @Override 620 public int hashCode() { 621 return maximumIntegerDigits * 37 + maxFractionDigits; 622 // just enough fields for a reasonable distribution 623 } 624 625 /** 626 * Overrides equals. 627 */ 628 @Override 629 public boolean equals(Object obj) { 630 if (obj == null) { 631 return false; 632 } 633 if (this == obj) { 634 return true; 635 } 636 if (getClass() != obj.getClass()) { 637 return false; 638 } 639 NumberFormat other = (NumberFormat) obj; 640 return (maximumIntegerDigits == other.maximumIntegerDigits 641 && minimumIntegerDigits == other.minimumIntegerDigits 642 && maximumFractionDigits == other.maximumFractionDigits 643 && minimumFractionDigits == other.minimumFractionDigits 644 && groupingUsed == other.groupingUsed 645 && parseIntegerOnly == other.parseIntegerOnly); 646 } 647 648 /** 649 * Overrides Cloneable. 650 */ 651 @Override 652 public Object clone() { 653 NumberFormat other = (NumberFormat) super.clone(); 654 return other; 655 } 656 657 /** 658 * Returns true if grouping is used in this format. For example, in the 659 * English locale, with grouping on, the number 1234567 might be formatted 660 * as "1,234,567". The grouping separator as well as the size of each group 661 * is locale dependant and is determined by sub-classes of NumberFormat. 662 * 663 * @return {@code true} if grouping is used; 664 * {@code false} otherwise 665 * @see #setGroupingUsed 666 */ 667 public boolean isGroupingUsed() { 668 return groupingUsed; 669 } 670 671 /** 672 * Set whether or not grouping will be used in this format. 673 * 674 * @param newValue {@code true} if grouping is used; 675 * {@code false} otherwise 676 * @see #isGroupingUsed 677 */ 678 public void setGroupingUsed(boolean newValue) { 679 groupingUsed = newValue; 680 } 681 682 /** 683 * Returns the maximum number of digits allowed in the integer portion of a 684 * number. 685 * 686 * @return the maximum number of digits 687 * @see #setMaximumIntegerDigits 688 */ 689 public int getMaximumIntegerDigits() { 690 return maximumIntegerDigits; 691 } 692 693 /** 694 * Sets the maximum number of digits allowed in the integer portion of a 695 * number. maximumIntegerDigits must be ≥ minimumIntegerDigits. If the 696 * new value for maximumIntegerDigits is less than the current value 697 * of minimumIntegerDigits, then minimumIntegerDigits will also be set to 698 * the new value. 699 * 700 * @param newValue the maximum number of integer digits to be shown; if 701 * less than zero, then zero is used. The concrete subclass may enforce an 702 * upper limit to this value appropriate to the numeric type being formatted. 703 * @see #getMaximumIntegerDigits 704 */ 705 public void setMaximumIntegerDigits(int newValue) { 706 maximumIntegerDigits = Math.max(0,newValue); 707 if (minimumIntegerDigits > maximumIntegerDigits) { 708 minimumIntegerDigits = maximumIntegerDigits; 709 } 710 } 711 712 /** 713 * Returns the minimum number of digits allowed in the integer portion of a 714 * number. 715 * 716 * @return the minimum number of digits 717 * @see #setMinimumIntegerDigits 718 */ 719 public int getMinimumIntegerDigits() { 720 return minimumIntegerDigits; 721 } 722 723 /** 724 * Sets the minimum number of digits allowed in the integer portion of a 725 * number. minimumIntegerDigits must be ≤ maximumIntegerDigits. If the 726 * new value for minimumIntegerDigits exceeds the current value 727 * of maximumIntegerDigits, then maximumIntegerDigits will also be set to 728 * the new value 729 * 730 * @param newValue the minimum number of integer digits to be shown; if 731 * less than zero, then zero is used. The concrete subclass may enforce an 732 * upper limit to this value appropriate to the numeric type being formatted. 733 * @see #getMinimumIntegerDigits 734 */ 735 public void setMinimumIntegerDigits(int newValue) { 736 minimumIntegerDigits = Math.max(0,newValue); 737 if (minimumIntegerDigits > maximumIntegerDigits) { 738 maximumIntegerDigits = minimumIntegerDigits; 739 } 740 } 741 742 /** 743 * Returns the maximum number of digits allowed in the fraction portion of a 744 * number. 745 * 746 * @return the maximum number of digits. 747 * @see #setMaximumFractionDigits 748 */ 749 public int getMaximumFractionDigits() { 750 return maximumFractionDigits; 751 } 752 753 /** 754 * Sets the maximum number of digits allowed in the fraction portion of a 755 * number. maximumFractionDigits must be ≥ minimumFractionDigits. If the 756 * new value for maximumFractionDigits is less than the current value 757 * of minimumFractionDigits, then minimumFractionDigits will also be set to 758 * the new value. 759 * 760 * @param newValue the maximum number of fraction digits to be shown; if 761 * less than zero, then zero is used. The concrete subclass may enforce an 762 * upper limit to this value appropriate to the numeric type being formatted. 763 * @see #getMaximumFractionDigits 764 */ 765 public void setMaximumFractionDigits(int newValue) { 766 maximumFractionDigits = Math.max(0,newValue); 767 if (maximumFractionDigits < minimumFractionDigits) { 768 minimumFractionDigits = maximumFractionDigits; 769 } 770 } 771 772 /** 773 * Returns the minimum number of digits allowed in the fraction portion of a 774 * number. 775 * 776 * @return the minimum number of digits 777 * @see #setMinimumFractionDigits 778 */ 779 public int getMinimumFractionDigits() { 780 return minimumFractionDigits; 781 } 782 783 /** 784 * Sets the minimum number of digits allowed in the fraction portion of a 785 * number. minimumFractionDigits must be ≤ maximumFractionDigits. If the 786 * new value for minimumFractionDigits exceeds the current value 787 * of maximumFractionDigits, then maximumIntegerDigits will also be set to 788 * the new value 789 * 790 * @param newValue the minimum number of fraction digits to be shown; if 791 * less than zero, then zero is used. The concrete subclass may enforce an 792 * upper limit to this value appropriate to the numeric type being formatted. 793 * @see #getMinimumFractionDigits 794 */ 795 public void setMinimumFractionDigits(int newValue) { 796 minimumFractionDigits = Math.max(0,newValue); 797 if (maximumFractionDigits < minimumFractionDigits) { 798 maximumFractionDigits = minimumFractionDigits; 799 } 800 } 801 802 /** 803 * Gets the currency used by this number format when formatting 804 * currency values. The initial value is derived in a locale dependent 805 * way. The returned value may be null if no valid 806 * currency could be determined and no currency has been set using 807 * {@link #setCurrency(java.util.Currency) setCurrency}. 808 * <p> 809 * The default implementation throws 810 * <code>UnsupportedOperationException</code>. 811 * 812 * @return the currency used by this number format, or <code>null</code> 813 * @exception UnsupportedOperationException if the number format class 814 * doesn't implement currency formatting 815 * @since 1.4 816 */ 817 public Currency getCurrency() { 818 throw new UnsupportedOperationException(); 819 } 820 821 /** 822 * Sets the currency used by this number format when formatting 823 * currency values. This does not update the minimum or maximum 824 * number of fraction digits used by the number format. 825 * <p> 826 * The default implementation throws 827 * <code>UnsupportedOperationException</code>. 828 * 829 * @param currency the new currency to be used by this number format 830 * @exception UnsupportedOperationException if the number format class 831 * doesn't implement currency formatting 832 * @exception NullPointerException if <code>currency</code> is null 833 * @since 1.4 834 */ 835 public void setCurrency(Currency currency) { 836 throw new UnsupportedOperationException(); 837 } 838 839 /** 840 * Gets the {@link java.math.RoundingMode} used in this NumberFormat. 841 * The default implementation of this method in NumberFormat 842 * always throws {@link java.lang.UnsupportedOperationException}. 843 * Subclasses which handle different rounding modes should override 844 * this method. 845 * 846 * @exception UnsupportedOperationException The default implementation 847 * always throws this exception 848 * @return The <code>RoundingMode</code> used for this NumberFormat. 849 * @see #setRoundingMode(RoundingMode) 850 * @since 1.6 851 */ 852 public RoundingMode getRoundingMode() { 853 throw new UnsupportedOperationException(); 854 } 855 856 /** 857 * Sets the {@link java.math.RoundingMode} used in this NumberFormat. 858 * The default implementation of this method in NumberFormat always 859 * throws {@link java.lang.UnsupportedOperationException}. 860 * Subclasses which handle different rounding modes should override 861 * this method. 862 * 863 * @exception UnsupportedOperationException The default implementation 864 * always throws this exception 865 * @exception NullPointerException if <code>roundingMode</code> is null 866 * @param roundingMode The <code>RoundingMode</code> to be used 867 * @see #getRoundingMode() 868 * @since 1.6 869 */ 870 public void setRoundingMode(RoundingMode roundingMode) { 871 throw new UnsupportedOperationException(); 872 } 873 874 // =======================privates=============================== 875 876 private static NumberFormat getInstance(Locale desiredLocale, 877 int choice) { 878 LocaleProviderAdapter adapter; 879 adapter = LocaleProviderAdapter.getAdapter(NumberFormatProvider.class, 880 desiredLocale); 881 NumberFormat numberFormat = getInstance(adapter, desiredLocale, choice); 882 if (numberFormat == null) { 883 numberFormat = getInstance(LocaleProviderAdapter.forJRE(), 884 desiredLocale, choice); 885 } 886 return numberFormat; 887 } 888 889 private static NumberFormat getInstance(LocaleProviderAdapter adapter, 890 Locale locale, int choice) { 891 NumberFormatProvider provider = adapter.getNumberFormatProvider(); 892 NumberFormat numberFormat = null; 893 switch (choice) { 894 case NUMBERSTYLE: 895 numberFormat = provider.getNumberInstance(locale); 896 break; 897 case PERCENTSTYLE: 898 numberFormat = provider.getPercentInstance(locale); 899 break; 900 case CURRENCYSTYLE: 901 numberFormat = provider.getCurrencyInstance(locale); 902 break; 903 case INTEGERSTYLE: 904 numberFormat = provider.getIntegerInstance(locale); 905 break; 906 } 907 return numberFormat; 908 } 909 910 /** 911 * First, read in the default serializable data. 912 * 913 * Then, if <code>serialVersionOnStream</code> is less than 1, indicating that 914 * the stream was written by JDK 1.1, 915 * set the <code>int</code> fields such as <code>maximumIntegerDigits</code> 916 * to be equal to the <code>byte</code> fields such as <code>maxIntegerDigits</code>, 917 * since the <code>int</code> fields were not present in JDK 1.1. 918 * Finally, set serialVersionOnStream back to the maximum allowed value so that 919 * default serialization will work properly if this object is streamed out again. 920 * 921 * <p>If <code>minimumIntegerDigits</code> is greater than 922 * <code>maximumIntegerDigits</code> or <code>minimumFractionDigits</code> 923 * is greater than <code>maximumFractionDigits</code>, then the stream data 924 * is invalid and this method throws an <code>InvalidObjectException</code>. 925 * In addition, if any of these values is negative, then this method throws 926 * an <code>InvalidObjectException</code>. 927 * 928 * @since 1.2 929 */ 930 private void readObject(ObjectInputStream stream) 931 throws IOException, ClassNotFoundException 932 { 933 stream.defaultReadObject(); 934 if (serialVersionOnStream < 1) { 935 // Didn't have additional int fields, reassign to use them. 936 maximumIntegerDigits = maxIntegerDigits; 937 minimumIntegerDigits = minIntegerDigits; 938 maximumFractionDigits = maxFractionDigits; 939 minimumFractionDigits = minFractionDigits; 940 } 941 if (minimumIntegerDigits > maximumIntegerDigits || 942 minimumFractionDigits > maximumFractionDigits || 943 minimumIntegerDigits < 0 || minimumFractionDigits < 0) { 944 throw new InvalidObjectException("Digit count range invalid"); 945 } 946 serialVersionOnStream = currentSerialVersion; 947 } 948 949 /** 950 * Write out the default serializable data, after first setting 951 * the <code>byte</code> fields such as <code>maxIntegerDigits</code> to be 952 * equal to the <code>int</code> fields such as <code>maximumIntegerDigits</code> 953 * (or to <code>Byte.MAX_VALUE</code>, whichever is smaller), for compatibility 954 * with the JDK 1.1 version of the stream format. 955 * 956 * @since 1.2 957 */ 958 private void writeObject(ObjectOutputStream stream) 959 throws IOException 960 { 961 maxIntegerDigits = (maximumIntegerDigits > Byte.MAX_VALUE) ? 962 Byte.MAX_VALUE : (byte)maximumIntegerDigits; 963 minIntegerDigits = (minimumIntegerDigits > Byte.MAX_VALUE) ? 964 Byte.MAX_VALUE : (byte)minimumIntegerDigits; 965 maxFractionDigits = (maximumFractionDigits > Byte.MAX_VALUE) ? 966 Byte.MAX_VALUE : (byte)maximumFractionDigits; 967 minFractionDigits = (minimumFractionDigits > Byte.MAX_VALUE) ? 968 Byte.MAX_VALUE : (byte)minimumFractionDigits; 969 stream.defaultWriteObject(); 970 } 971 972 // Constants used by factory methods to specify a style of format. 973 private static final int NUMBERSTYLE = 0; 974 private static final int CURRENCYSTYLE = 1; 975 private static final int PERCENTSTYLE = 2; 976 private static final int SCIENTIFICSTYLE = 3; 977 private static final int INTEGERSTYLE = 4; 978 979 /** 980 * True if the grouping (i.e. thousands) separator is used when 981 * formatting and parsing numbers. 982 * 983 * @serial 984 * @see #isGroupingUsed 985 */ 986 private boolean groupingUsed = true; 987 988 /** 989 * The maximum number of digits allowed in the integer portion of a 990 * number. <code>maxIntegerDigits</code> must be greater than or equal to 991 * <code>minIntegerDigits</code>. 992 * <p> 993 * <strong>Note:</strong> This field exists only for serialization 994 * compatibility with JDK 1.1. In Java platform 2 v1.2 and higher, the new 995 * <code>int</code> field <code>maximumIntegerDigits</code> is used instead. 996 * When writing to a stream, <code>maxIntegerDigits</code> is set to 997 * <code>maximumIntegerDigits</code> or <code>Byte.MAX_VALUE</code>, 998 * whichever is smaller. When reading from a stream, this field is used 999 * only if <code>serialVersionOnStream</code> is less than 1. 1000 * 1001 * @serial 1002 * @see #getMaximumIntegerDigits 1003 */ 1004 private byte maxIntegerDigits = 40; 1005 1006 /** 1007 * The minimum number of digits allowed in the integer portion of a 1008 * number. <code>minimumIntegerDigits</code> must be less than or equal to 1009 * <code>maximumIntegerDigits</code>. 1010 * <p> 1011 * <strong>Note:</strong> This field exists only for serialization 1012 * compatibility with JDK 1.1. In Java platform 2 v1.2 and higher, the new 1013 * <code>int</code> field <code>minimumIntegerDigits</code> is used instead. 1014 * When writing to a stream, <code>minIntegerDigits</code> is set to 1015 * <code>minimumIntegerDigits</code> or <code>Byte.MAX_VALUE</code>, 1016 * whichever is smaller. When reading from a stream, this field is used 1017 * only if <code>serialVersionOnStream</code> is less than 1. 1018 * 1019 * @serial 1020 * @see #getMinimumIntegerDigits 1021 */ 1022 private byte minIntegerDigits = 1; 1023 1024 /** 1025 * The maximum number of digits allowed in the fractional portion of a 1026 * number. <code>maximumFractionDigits</code> must be greater than or equal to 1027 * <code>minimumFractionDigits</code>. 1028 * <p> 1029 * <strong>Note:</strong> This field exists only for serialization 1030 * compatibility with JDK 1.1. In Java platform 2 v1.2 and higher, the new 1031 * <code>int</code> field <code>maximumFractionDigits</code> is used instead. 1032 * When writing to a stream, <code>maxFractionDigits</code> is set to 1033 * <code>maximumFractionDigits</code> or <code>Byte.MAX_VALUE</code>, 1034 * whichever is smaller. When reading from a stream, this field is used 1035 * only if <code>serialVersionOnStream</code> is less than 1. 1036 * 1037 * @serial 1038 * @see #getMaximumFractionDigits 1039 */ 1040 private byte maxFractionDigits = 3; // invariant, >= minFractionDigits 1041 1042 /** 1043 * The minimum number of digits allowed in the fractional portion of a 1044 * number. <code>minimumFractionDigits</code> must be less than or equal to 1045 * <code>maximumFractionDigits</code>. 1046 * <p> 1047 * <strong>Note:</strong> This field exists only for serialization 1048 * compatibility with JDK 1.1. In Java platform 2 v1.2 and higher, the new 1049 * <code>int</code> field <code>minimumFractionDigits</code> is used instead. 1050 * When writing to a stream, <code>minFractionDigits</code> is set to 1051 * <code>minimumFractionDigits</code> or <code>Byte.MAX_VALUE</code>, 1052 * whichever is smaller. When reading from a stream, this field is used 1053 * only if <code>serialVersionOnStream</code> is less than 1. 1054 * 1055 * @serial 1056 * @see #getMinimumFractionDigits 1057 */ 1058 private byte minFractionDigits = 0; 1059 1060 /** 1061 * True if this format will parse numbers as integers only. 1062 * 1063 * @serial 1064 * @see #isParseIntegerOnly 1065 */ 1066 private boolean parseIntegerOnly = false; 1067 1068 // new fields for 1.2. byte is too small for integer digits. 1069 1070 /** 1071 * The maximum number of digits allowed in the integer portion of a 1072 * number. <code>maximumIntegerDigits</code> must be greater than or equal to 1073 * <code>minimumIntegerDigits</code>. 1074 * 1075 * @serial 1076 * @since 1.2 1077 * @see #getMaximumIntegerDigits 1078 */ 1079 private int maximumIntegerDigits = 40; 1080 1081 /** 1082 * The minimum number of digits allowed in the integer portion of a 1083 * number. <code>minimumIntegerDigits</code> must be less than or equal to 1084 * <code>maximumIntegerDigits</code>. 1085 * 1086 * @serial 1087 * @since 1.2 1088 * @see #getMinimumIntegerDigits 1089 */ 1090 private int minimumIntegerDigits = 1; 1091 1092 /** 1093 * The maximum number of digits allowed in the fractional portion of a 1094 * number. <code>maximumFractionDigits</code> must be greater than or equal to 1095 * <code>minimumFractionDigits</code>. 1096 * 1097 * @serial 1098 * @since 1.2 1099 * @see #getMaximumFractionDigits 1100 */ 1101 private int maximumFractionDigits = 3; // invariant, >= minFractionDigits 1102 1103 /** 1104 * The minimum number of digits allowed in the fractional portion of a 1105 * number. <code>minimumFractionDigits</code> must be less than or equal to 1106 * <code>maximumFractionDigits</code>. 1107 * 1108 * @serial 1109 * @since 1.2 1110 * @see #getMinimumFractionDigits 1111 */ 1112 private int minimumFractionDigits = 0; 1113 1114 static final int currentSerialVersion = 1; 1115 1116 /** 1117 * Describes the version of <code>NumberFormat</code> present on the stream. 1118 * Possible values are: 1119 * <ul> 1120 * <li><b>0</b> (or uninitialized): the JDK 1.1 version of the stream format. 1121 * In this version, the <code>int</code> fields such as 1122 * <code>maximumIntegerDigits</code> were not present, and the <code>byte</code> 1123 * fields such as <code>maxIntegerDigits</code> are used instead. 1124 * 1125 * <li><b>1</b>: the 1.2 version of the stream format. The values of the 1126 * <code>byte</code> fields such as <code>maxIntegerDigits</code> are ignored, 1127 * and the <code>int</code> fields such as <code>maximumIntegerDigits</code> 1128 * are used instead. 1129 * </ul> 1130 * When streaming out a <code>NumberFormat</code>, the most recent format 1131 * (corresponding to the highest allowable <code>serialVersionOnStream</code>) 1132 * is always written. 1133 * 1134 * @serial 1135 * @since 1.2 1136 */ 1137 private int serialVersionOnStream = currentSerialVersion; 1138 1139 // Removed "implements Cloneable" clause. Needs to update serialization 1140 // ID for backward compatibility. 1141 static final long serialVersionUID = -2308460125733713944L; 1142 1143 1144 // 1145 // class for AttributedCharacterIterator attributes 1146 // 1147 /** 1148 * Defines constants that are used as attribute keys in the 1149 * <code>AttributedCharacterIterator</code> returned 1150 * from <code>NumberFormat.formatToCharacterIterator</code> and as 1151 * field identifiers in <code>FieldPosition</code>. 1152 * 1153 * @since 1.4 1154 */ 1155 public static class Field extends Format.Field { 1156 1157 // Proclaim serial compatibility with 1.4 FCS 1158 private static final long serialVersionUID = 7494728892700160890L; 1159 1160 // table of all instances in this class, used by readResolve 1161 private static final Map<String, Field> instanceMap = new HashMap<>(11); 1162 1163 /** 1164 * Creates a Field instance with the specified 1165 * name. 1166 * 1167 * @param name Name of the attribute 1168 */ 1169 protected Field(String name) { 1170 super(name); 1171 if (this.getClass() == NumberFormat.Field.class) { 1172 instanceMap.put(name, this); 1173 } 1174 } 1175 1176 /** 1177 * Resolves instances being deserialized to the predefined constants. 1178 * 1179 * @throws InvalidObjectException if the constant could not be resolved. 1180 * @return resolved NumberFormat.Field constant 1181 */ 1182 @Override 1183 protected Object readResolve() throws InvalidObjectException { 1184 if (this.getClass() != NumberFormat.Field.class) { 1185 throw new InvalidObjectException("subclass didn't correctly implement readResolve"); 1186 } 1187 1188 Object instance = instanceMap.get(getName()); 1189 if (instance != null) { 1190 return instance; 1191 } else { 1192 throw new InvalidObjectException("unknown attribute name"); 1193 } 1194 } 1195 1196 /** 1197 * Constant identifying the integer field. 1198 */ 1199 public static final Field INTEGER = new Field("integer"); 1200 1201 /** 1202 * Constant identifying the fraction field. 1203 */ 1204 public static final Field FRACTION = new Field("fraction"); 1205 1206 /** 1207 * Constant identifying the exponent field. 1208 */ 1209 public static final Field EXPONENT = new Field("exponent"); 1210 1211 /** 1212 * Constant identifying the decimal separator field. 1213 */ 1214 public static final Field DECIMAL_SEPARATOR = 1215 new Field("decimal separator"); 1216 1217 /** 1218 * Constant identifying the sign field. 1219 */ 1220 public static final Field SIGN = new Field("sign"); 1221 1222 /** 1223 * Constant identifying the grouping separator field. 1224 */ 1225 public static final Field GROUPING_SEPARATOR = 1226 new Field("grouping separator"); 1227 1228 /** 1229 * Constant identifying the exponent symbol field. 1230 */ 1231 public static final Field EXPONENT_SYMBOL = new 1232 Field("exponent symbol"); 1233 1234 /** 1235 * Constant identifying the percent field. 1236 */ 1237 public static final Field PERCENT = new Field("percent"); 1238 1239 /** 1240 * Constant identifying the permille field. 1241 */ 1242 public static final Field PERMILLE = new Field("per mille"); 1243 1244 /** 1245 * Constant identifying the currency field. 1246 */ 1247 public static final Field CURRENCY = new Field("currency"); 1248 1249 /** 1250 * Constant identifying the exponent sign field. 1251 */ 1252 public static final Field EXPONENT_SIGN = new Field("exponent sign"); 1253 } 1254 }