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 * @see DecimalFormat 185 * @see ChoiceFormat 186 * @author Mark Davis 187 * @author Helena Shih 188 * @since 1.1 189 */ 190 public abstract class NumberFormat extends Format { 191 192 /** 193 * Field constant used to construct a FieldPosition object. Signifies that 194 * the position of the integer part of a formatted number should be returned. 195 * @see java.text.FieldPosition 196 */ 197 public static final int INTEGER_FIELD = 0; 198 199 /** 200 * Field constant used to construct a FieldPosition object. Signifies that 201 * the position of the fraction part of a formatted number should be returned. 202 * @see java.text.FieldPosition 203 */ 204 public static final int FRACTION_FIELD = 1; 205 206 /** 207 * Sole constructor. (For invocation by subclass constructors, typically 208 * implicit.) 209 */ 210 protected NumberFormat() { 211 } 212 213 /** 214 * Formats a number and appends the resulting text to the given string 215 * buffer. 216 * The number can be of any subclass of {@link java.lang.Number}. 217 * <p> 218 * This implementation extracts the number's value using 219 * {@link java.lang.Number#longValue()} for all integral type values that 220 * can be converted to <code>long</code> without loss of information, 221 * including <code>BigInteger</code> values with a 222 * {@link java.math.BigInteger#bitLength() bit length} of less than 64, 223 * and {@link java.lang.Number#doubleValue()} for all other types. It 224 * then calls 225 * {@link #format(long,java.lang.StringBuffer,java.text.FieldPosition)} 226 * or {@link #format(double,java.lang.StringBuffer,java.text.FieldPosition)}. 227 * This may result in loss of magnitude information and precision for 228 * <code>BigInteger</code> and <code>BigDecimal</code> values. 229 * @param number the number to format 230 * @param toAppendTo the <code>StringBuffer</code> to which the formatted 231 * text is to be appended 232 * @param pos On input: an alignment field, if desired. 233 * On output: the offsets of the alignment field. 234 * @return the value passed in as <code>toAppendTo</code> 235 * @exception IllegalArgumentException if <code>number</code> is 236 * null or not an instance of <code>Number</code>. 237 * @exception NullPointerException if <code>toAppendTo</code> or 238 * <code>pos</code> is null 239 * @exception ArithmeticException if rounding is needed with rounding 240 * mode being set to RoundingMode.UNNECESSARY 241 * @see java.text.FieldPosition 242 */ 243 @Override 244 public StringBuffer format(Object number, 245 StringBuffer toAppendTo, 246 FieldPosition pos) { 247 if (number instanceof Long || number instanceof Integer || 248 number instanceof Short || number instanceof Byte || 249 number instanceof AtomicInteger || number instanceof AtomicLong || 250 (number instanceof BigInteger && 251 ((BigInteger)number).bitLength() < 64)) { 252 return format(((Number)number).longValue(), toAppendTo, pos); 253 } else if (number instanceof Number) { 254 return format(((Number)number).doubleValue(), toAppendTo, pos); 255 } else { 256 throw new IllegalArgumentException("Cannot format given Object as a Number"); 257 } 258 } 259 260 /** 261 * Parses text from a string to produce a <code>Number</code>. 262 * <p> 263 * The method attempts to parse text starting at the index given by 264 * <code>pos</code>. 265 * If parsing succeeds, then the index of <code>pos</code> is updated 266 * to the index after the last character used (parsing does not necessarily 267 * use all characters up to the end of the string), and the parsed 268 * number is returned. The updated <code>pos</code> can be used to 269 * indicate the starting point for the next call to this method. 270 * If an error occurs, then the index of <code>pos</code> is not 271 * changed, the error index of <code>pos</code> is set to the index of 272 * the character where the error occurred, and null is returned. 273 * <p> 274 * See the {@link #parse(String, ParsePosition)} method for more information 275 * on number parsing. 276 * 277 * @param source A <code>String</code>, part of which should be parsed. 278 * @param pos A <code>ParsePosition</code> object with index and error 279 * index information as described above. 280 * @return A <code>Number</code> parsed from the string. In case of 281 * error, returns null. 282 * @throws NullPointerException if {@code source} or {@code pos} is null. 283 */ 284 @Override 285 public final Object parseObject(String source, ParsePosition pos) { 286 return parse(source, pos); 287 } 288 289 /** 290 * Specialization of format. 291 * 292 * @param number the double number to format 293 * @return the formatted String 294 * @exception ArithmeticException if rounding is needed with rounding 295 * mode being set to RoundingMode.UNNECESSARY 296 * @see java.text.Format#format 297 */ 298 public final String format(double number) { 299 // Use fast-path for double result if that works 300 String result = fastFormat(number); 301 if (result != null) 302 return result; 303 304 return format(number, new StringBuffer(), 305 DontCareFieldPosition.INSTANCE).toString(); 306 } 307 308 /* 309 * fastFormat() is supposed to be implemented in concrete subclasses only. 310 * Default implem always returns null. 311 */ 312 String fastFormat(double number) { return null; } 313 314 /** 315 * Specialization of format. 316 * 317 * @param number the long number to format 318 * @return the formatted String 319 * @exception ArithmeticException if rounding is needed with rounding 320 * mode being set to RoundingMode.UNNECESSARY 321 * @see java.text.Format#format 322 */ 323 public final String format(long number) { 324 return format(number, new StringBuffer(), 325 DontCareFieldPosition.INSTANCE).toString(); 326 } 327 328 /** 329 * Specialization of format. 330 * 331 * @param number the double number to format 332 * @param toAppendTo the StringBuffer to which the formatted text is to be 333 * appended 334 * @param pos the field position 335 * @return the formatted StringBuffer 336 * @exception ArithmeticException if rounding is needed with rounding 337 * mode being set to RoundingMode.UNNECESSARY 338 * @see java.text.Format#format 339 */ 340 public abstract StringBuffer format(double number, 341 StringBuffer toAppendTo, 342 FieldPosition pos); 343 344 /** 345 * Specialization of format. 346 * 347 * @param number the long number to format 348 * @param toAppendTo the StringBuffer to which the formatted text is to be 349 * appended 350 * @param pos the field position 351 * @return the formatted StringBuffer 352 * @exception ArithmeticException if rounding is needed with rounding 353 * mode being set to RoundingMode.UNNECESSARY 354 * @see java.text.Format#format 355 */ 356 public abstract StringBuffer format(long number, 357 StringBuffer toAppendTo, 358 FieldPosition pos); 359 360 /** 361 * Returns a Long if possible (e.g., within the range [Long.MIN_VALUE, 362 * Long.MAX_VALUE] and with no decimals), otherwise a Double. 363 * If IntegerOnly is set, will stop at a decimal 364 * point (or equivalent; e.g., for rational numbers "1 2/3", will stop 365 * after the 1). 366 * Does not throw an exception; if no object can be parsed, index is 367 * unchanged! 368 * 369 * @param source the String to parse 370 * @param parsePosition the parse position 371 * @return the parsed value 372 * @see java.text.NumberFormat#isParseIntegerOnly 373 * @see java.text.Format#parseObject 374 */ 375 public abstract Number parse(String source, ParsePosition parsePosition); 376 377 /** 378 * Parses text from the beginning of the given string to produce a number. 379 * The method may not use the entire text of the given string. 380 * <p> 381 * See the {@link #parse(String, ParsePosition)} method for more information 382 * on number parsing. 383 * 384 * @param source A <code>String</code> whose beginning should be parsed. 385 * @return A <code>Number</code> parsed from the string. 386 * @exception ParseException if the beginning of the specified string 387 * cannot be parsed. 388 */ 389 public Number parse(String source) throws ParseException { 390 ParsePosition parsePosition = new ParsePosition(0); 391 Number result = parse(source, parsePosition); 392 if (parsePosition.index == 0) { 393 throw new ParseException("Unparseable number: \"" + source + "\"", 394 parsePosition.errorIndex); 395 } 396 return result; 397 } 398 399 /** 400 * Returns true if this format will parse numbers as integers only. 401 * For example in the English locale, with ParseIntegerOnly true, the 402 * string "1234." would be parsed as the integer value 1234 and parsing 403 * would stop at the "." character. Of course, the exact format accepted 404 * by the parse operation is locale dependant and determined by sub-classes 405 * of NumberFormat. 406 * 407 * @return {@code true} if numbers should be parsed as integers only; 408 * {@code false} otherwise 409 */ 410 public boolean isParseIntegerOnly() { 411 return parseIntegerOnly; 412 } 413 414 /** 415 * Sets whether or not numbers should be parsed as integers only. 416 * 417 * @param value {@code true} if numbers should be parsed as integers only; 418 * {@code false} otherwise 419 * @see #isParseIntegerOnly 420 */ 421 public void setParseIntegerOnly(boolean value) { 422 parseIntegerOnly = value; 423 } 424 425 //============== Locale Stuff ===================== 426 427 /** 428 * Returns a general-purpose number format for the current default 429 * {@link java.util.Locale.Category#FORMAT FORMAT} locale. 430 * This is the same as calling 431 * {@link #getNumberInstance() getNumberInstance()}. 432 * 433 * @return the {@code NumberFormat} instance for general-purpose number 434 * formatting 435 */ 436 public static final NumberFormat getInstance() { 437 return getInstance(Locale.getDefault(Locale.Category.FORMAT), NUMBERSTYLE); 438 } 439 440 /** 441 * Returns a general-purpose number format for the specified locale. 442 * This is the same as calling 443 * {@link #getNumberInstance(java.util.Locale) getNumberInstance(inLocale)}. 444 * 445 * @param inLocale the desired locale 446 * @return the {@code NumberFormat} instance for general-purpose number 447 * formatting 448 */ 449 public static NumberFormat getInstance(Locale inLocale) { 450 return getInstance(inLocale, NUMBERSTYLE); 451 } 452 453 /** 454 * Returns a general-purpose number format for the current default 455 * {@link java.util.Locale.Category#FORMAT FORMAT} locale. 456 * <p>This is equivalent to calling 457 * {@link #getNumberInstance(Locale) 458 * getNumberInstance(Locale.getDefault(Locale.Category.FORMAT))}. 459 * 460 * @return the {@code NumberFormat} instance for general-purpose number 461 * formatting 462 * @see java.util.Locale#getDefault(java.util.Locale.Category) 463 * @see java.util.Locale.Category#FORMAT 464 */ 465 public static final NumberFormat getNumberInstance() { 466 return getInstance(Locale.getDefault(Locale.Category.FORMAT), NUMBERSTYLE); 467 } 468 469 /** 470 * Returns a general-purpose number format for the specified locale. 471 * 472 * @param inLocale the desired locale 473 * @return the {@code NumberFormat} instance for general-purpose number 474 * formatting 475 */ 476 public static NumberFormat getNumberInstance(Locale inLocale) { 477 return getInstance(inLocale, NUMBERSTYLE); 478 } 479 480 /** 481 * Returns an integer number format for the current default 482 * {@link java.util.Locale.Category#FORMAT FORMAT} locale. The 483 * returned number format is configured to round floating point numbers 484 * to the nearest integer using half-even rounding (see {@link 485 * java.math.RoundingMode#HALF_EVEN RoundingMode.HALF_EVEN}) for formatting, 486 * and to parse only the integer part of an input string (see {@link 487 * #isParseIntegerOnly isParseIntegerOnly}). 488 * <p>This is equivalent to calling 489 * {@link #getIntegerInstance(Locale) 490 * getIntegerInstance(Locale.getDefault(Locale.Category.FORMAT))}. 491 * 492 * @see #getRoundingMode() 493 * @see java.util.Locale#getDefault(java.util.Locale.Category) 494 * @see java.util.Locale.Category#FORMAT 495 * @return a number format for integer values 496 * @since 1.4 497 */ 498 public static final NumberFormat getIntegerInstance() { 499 return getInstance(Locale.getDefault(Locale.Category.FORMAT), INTEGERSTYLE); 500 } 501 502 /** 503 * Returns an integer number format for the specified locale. The 504 * returned number format is configured to round floating point numbers 505 * to the nearest integer using half-even rounding (see {@link 506 * java.math.RoundingMode#HALF_EVEN RoundingMode.HALF_EVEN}) for formatting, 507 * and to parse only the integer part of an input string (see {@link 508 * #isParseIntegerOnly isParseIntegerOnly}). 509 * 510 * @param inLocale the desired locale 511 * @see #getRoundingMode() 512 * @return a number format for integer values 513 * @since 1.4 514 */ 515 public static NumberFormat getIntegerInstance(Locale inLocale) { 516 return getInstance(inLocale, INTEGERSTYLE); 517 } 518 519 /** 520 * Returns a currency format for the current default 521 * {@link java.util.Locale.Category#FORMAT FORMAT} locale. 522 * <p>This is equivalent to calling 523 * {@link #getCurrencyInstance(Locale) 524 * getCurrencyInstance(Locale.getDefault(Locale.Category.FORMAT))}. 525 * 526 * @return the {@code NumberFormat} instance for currency formatting 527 * @see java.util.Locale#getDefault(java.util.Locale.Category) 528 * @see java.util.Locale.Category#FORMAT 529 */ 530 public static final NumberFormat getCurrencyInstance() { 531 return getInstance(Locale.getDefault(Locale.Category.FORMAT), CURRENCYSTYLE); 532 } 533 534 /** 535 * Returns a currency format for the specified locale. 536 * 537 * @param inLocale the desired locale 538 * @return the {@code NumberFormat} instance for currency formatting 539 */ 540 public static NumberFormat getCurrencyInstance(Locale inLocale) { 541 return getInstance(inLocale, CURRENCYSTYLE); 542 } 543 544 /** 545 * Returns a percentage format for the current default 546 * {@link java.util.Locale.Category#FORMAT FORMAT} locale. 547 * <p>This is equivalent to calling 548 * {@link #getPercentInstance(Locale) 549 * getPercentInstance(Locale.getDefault(Locale.Category.FORMAT))}. 550 * 551 * @return the {@code NumberFormat} instance for percentage formatting 552 * @see java.util.Locale#getDefault(java.util.Locale.Category) 553 * @see java.util.Locale.Category#FORMAT 554 */ 555 public static final NumberFormat getPercentInstance() { 556 return getInstance(Locale.getDefault(Locale.Category.FORMAT), PERCENTSTYLE); 557 } 558 559 /** 560 * Returns a percentage format for the specified locale. 561 * 562 * @param inLocale the desired locale 563 * @return the {@code NumberFormat} instance for percentage formatting 564 */ 565 public static NumberFormat getPercentInstance(Locale inLocale) { 566 return getInstance(inLocale, PERCENTSTYLE); 567 } 568 569 /** 570 * Returns a scientific format for the current default locale. 571 */ 572 /*public*/ final static NumberFormat getScientificInstance() { 573 return getInstance(Locale.getDefault(Locale.Category.FORMAT), SCIENTIFICSTYLE); 574 } 575 576 /** 577 * Returns a scientific format for the specified locale. 578 * 579 * @param inLocale the desired locale 580 */ 581 /*public*/ static NumberFormat getScientificInstance(Locale inLocale) { 582 return getInstance(inLocale, SCIENTIFICSTYLE); 583 } 584 585 /** 586 * Returns an array of all locales for which the 587 * <code>get*Instance</code> methods of this class can return 588 * localized instances. 589 * The returned array represents the union of locales supported by the Java 590 * runtime and by installed 591 * {@link java.text.spi.NumberFormatProvider NumberFormatProvider} implementations. 592 * It must contain at least a <code>Locale</code> instance equal to 593 * {@link java.util.Locale#US Locale.US}. 594 * 595 * @return An array of locales for which localized 596 * <code>NumberFormat</code> instances are available. 597 */ 598 public static Locale[] getAvailableLocales() { 599 LocaleServiceProviderPool pool = 600 LocaleServiceProviderPool.getPool(NumberFormatProvider.class); 601 return pool.getAvailableLocales(); 602 } 603 604 /** 605 * Overrides hashCode. 606 */ 607 @Override 608 public int hashCode() { 609 return maximumIntegerDigits * 37 + maxFractionDigits; 610 // just enough fields for a reasonable distribution 611 } 612 613 /** 614 * Overrides equals. 615 */ 616 @Override 617 public boolean equals(Object obj) { 618 if (obj == null) { 619 return false; 620 } 621 if (this == obj) { 622 return true; 623 } 624 if (getClass() != obj.getClass()) { 625 return false; 626 } 627 NumberFormat other = (NumberFormat) obj; 628 return (maximumIntegerDigits == other.maximumIntegerDigits 629 && minimumIntegerDigits == other.minimumIntegerDigits 630 && maximumFractionDigits == other.maximumFractionDigits 631 && minimumFractionDigits == other.minimumFractionDigits 632 && groupingUsed == other.groupingUsed 633 && parseIntegerOnly == other.parseIntegerOnly); 634 } 635 636 /** 637 * Overrides Cloneable. 638 */ 639 @Override 640 public Object clone() { 641 NumberFormat other = (NumberFormat) super.clone(); 642 return other; 643 } 644 645 /** 646 * Returns true if grouping is used in this format. For example, in the 647 * English locale, with grouping on, the number 1234567 might be formatted 648 * as "1,234,567". The grouping separator as well as the size of each group 649 * is locale dependant and is determined by sub-classes of NumberFormat. 650 * 651 * @return {@code true} if grouping is used; 652 * {@code false} otherwise 653 * @see #setGroupingUsed 654 */ 655 public boolean isGroupingUsed() { 656 return groupingUsed; 657 } 658 659 /** 660 * Set whether or not grouping will be used in this format. 661 * 662 * @param newValue {@code true} if grouping is used; 663 * {@code false} otherwise 664 * @see #isGroupingUsed 665 */ 666 public void setGroupingUsed(boolean newValue) { 667 groupingUsed = newValue; 668 } 669 670 /** 671 * Returns the maximum number of digits allowed in the integer portion of a 672 * number. 673 * 674 * @return the maximum number of digits 675 * @see #setMaximumIntegerDigits 676 */ 677 public int getMaximumIntegerDigits() { 678 return maximumIntegerDigits; 679 } 680 681 /** 682 * Sets the maximum number of digits allowed in the integer portion of a 683 * number. maximumIntegerDigits must be ≥ minimumIntegerDigits. If the 684 * new value for maximumIntegerDigits is less than the current value 685 * of minimumIntegerDigits, then minimumIntegerDigits will also be set to 686 * the new value. 687 * 688 * @param newValue the maximum number of integer digits to be shown; if 689 * less than zero, then zero is used. The concrete subclass may enforce an 690 * upper limit to this value appropriate to the numeric type being formatted. 691 * @see #getMaximumIntegerDigits 692 */ 693 public void setMaximumIntegerDigits(int newValue) { 694 maximumIntegerDigits = Math.max(0,newValue); 695 if (minimumIntegerDigits > maximumIntegerDigits) { 696 minimumIntegerDigits = maximumIntegerDigits; 697 } 698 } 699 700 /** 701 * Returns the minimum number of digits allowed in the integer portion of a 702 * number. 703 * 704 * @return the minimum number of digits 705 * @see #setMinimumIntegerDigits 706 */ 707 public int getMinimumIntegerDigits() { 708 return minimumIntegerDigits; 709 } 710 711 /** 712 * Sets the minimum number of digits allowed in the integer portion of a 713 * number. minimumIntegerDigits must be ≤ maximumIntegerDigits. If the 714 * new value for minimumIntegerDigits exceeds the current value 715 * of maximumIntegerDigits, then maximumIntegerDigits will also be set to 716 * the new value 717 * 718 * @param newValue the minimum number of integer digits to be shown; if 719 * less than zero, then zero is used. The concrete subclass may enforce an 720 * upper limit to this value appropriate to the numeric type being formatted. 721 * @see #getMinimumIntegerDigits 722 */ 723 public void setMinimumIntegerDigits(int newValue) { 724 minimumIntegerDigits = Math.max(0,newValue); 725 if (minimumIntegerDigits > maximumIntegerDigits) { 726 maximumIntegerDigits = minimumIntegerDigits; 727 } 728 } 729 730 /** 731 * Returns the maximum number of digits allowed in the fraction portion of a 732 * number. 733 * 734 * @return the maximum number of digits. 735 * @see #setMaximumFractionDigits 736 */ 737 public int getMaximumFractionDigits() { 738 return maximumFractionDigits; 739 } 740 741 /** 742 * Sets the maximum number of digits allowed in the fraction portion of a 743 * number. maximumFractionDigits must be ≥ minimumFractionDigits. If the 744 * new value for maximumFractionDigits is less than the current value 745 * of minimumFractionDigits, then minimumFractionDigits will also be set to 746 * the new value. 747 * 748 * @param newValue the maximum number of fraction digits to be shown; if 749 * less than zero, then zero is used. The concrete subclass may enforce an 750 * upper limit to this value appropriate to the numeric type being formatted. 751 * @see #getMaximumFractionDigits 752 */ 753 public void setMaximumFractionDigits(int newValue) { 754 maximumFractionDigits = Math.max(0,newValue); 755 if (maximumFractionDigits < minimumFractionDigits) { 756 minimumFractionDigits = maximumFractionDigits; 757 } 758 } 759 760 /** 761 * Returns the minimum number of digits allowed in the fraction portion of a 762 * number. 763 * 764 * @return the minimum number of digits 765 * @see #setMinimumFractionDigits 766 */ 767 public int getMinimumFractionDigits() { 768 return minimumFractionDigits; 769 } 770 771 /** 772 * Sets the minimum number of digits allowed in the fraction portion of a 773 * number. minimumFractionDigits must be ≤ maximumFractionDigits. If the 774 * new value for minimumFractionDigits exceeds the current value 775 * of maximumFractionDigits, then maximumIntegerDigits will also be set to 776 * the new value 777 * 778 * @param newValue the minimum number of fraction digits to be shown; if 779 * less than zero, then zero is used. The concrete subclass may enforce an 780 * upper limit to this value appropriate to the numeric type being formatted. 781 * @see #getMinimumFractionDigits 782 */ 783 public void setMinimumFractionDigits(int newValue) { 784 minimumFractionDigits = Math.max(0,newValue); 785 if (maximumFractionDigits < minimumFractionDigits) { 786 maximumFractionDigits = minimumFractionDigits; 787 } 788 } 789 790 /** 791 * Gets the currency used by this number format when formatting 792 * currency values. The initial value is derived in a locale dependent 793 * way. The returned value may be null if no valid 794 * currency could be determined and no currency has been set using 795 * {@link #setCurrency(java.util.Currency) setCurrency}. 796 * <p> 797 * The default implementation throws 798 * <code>UnsupportedOperationException</code>. 799 * 800 * @return the currency used by this number format, or <code>null</code> 801 * @exception UnsupportedOperationException if the number format class 802 * doesn't implement currency formatting 803 * @since 1.4 804 */ 805 public Currency getCurrency() { 806 throw new UnsupportedOperationException(); 807 } 808 809 /** 810 * Sets the currency used by this number format when formatting 811 * currency values. This does not update the minimum or maximum 812 * number of fraction digits used by the number format. 813 * <p> 814 * The default implementation throws 815 * <code>UnsupportedOperationException</code>. 816 * 817 * @param currency the new currency to be used by this number format 818 * @exception UnsupportedOperationException if the number format class 819 * doesn't implement currency formatting 820 * @exception NullPointerException if <code>currency</code> is null 821 * @since 1.4 822 */ 823 public void setCurrency(Currency currency) { 824 throw new UnsupportedOperationException(); 825 } 826 827 /** 828 * Gets the {@link java.math.RoundingMode} used in this NumberFormat. 829 * The default implementation of this method in NumberFormat 830 * always throws {@link java.lang.UnsupportedOperationException}. 831 * Subclasses which handle different rounding modes should override 832 * this method. 833 * 834 * @exception UnsupportedOperationException The default implementation 835 * always throws this exception 836 * @return The <code>RoundingMode</code> used for this NumberFormat. 837 * @see #setRoundingMode(RoundingMode) 838 * @since 1.6 839 */ 840 public RoundingMode getRoundingMode() { 841 throw new UnsupportedOperationException(); 842 } 843 844 /** 845 * Sets the {@link java.math.RoundingMode} used in this NumberFormat. 846 * The default implementation of this method in NumberFormat always 847 * throws {@link java.lang.UnsupportedOperationException}. 848 * Subclasses which handle different rounding modes should override 849 * this method. 850 * 851 * @exception UnsupportedOperationException The default implementation 852 * always throws this exception 853 * @exception NullPointerException if <code>roundingMode</code> is null 854 * @param roundingMode The <code>RoundingMode</code> to be used 855 * @see #getRoundingMode() 856 * @since 1.6 857 */ 858 public void setRoundingMode(RoundingMode roundingMode) { 859 throw new UnsupportedOperationException(); 860 } 861 862 // =======================privates=============================== 863 864 private static NumberFormat getInstance(Locale desiredLocale, 865 int choice) { 866 LocaleProviderAdapter adapter; 867 adapter = LocaleProviderAdapter.getAdapter(NumberFormatProvider.class, 868 desiredLocale); 869 NumberFormat numberFormat = getInstance(adapter, desiredLocale, choice); 870 if (numberFormat == null) { 871 numberFormat = getInstance(LocaleProviderAdapter.forJRE(), 872 desiredLocale, choice); 873 } 874 return numberFormat; 875 } 876 877 private static NumberFormat getInstance(LocaleProviderAdapter adapter, 878 Locale locale, int choice) { 879 NumberFormatProvider provider = adapter.getNumberFormatProvider(); 880 NumberFormat numberFormat = null; 881 switch (choice) { 882 case NUMBERSTYLE: 883 numberFormat = provider.getNumberInstance(locale); 884 break; 885 case PERCENTSTYLE: 886 numberFormat = provider.getPercentInstance(locale); 887 break; 888 case CURRENCYSTYLE: 889 numberFormat = provider.getCurrencyInstance(locale); 890 break; 891 case INTEGERSTYLE: 892 numberFormat = provider.getIntegerInstance(locale); 893 break; 894 } 895 return numberFormat; 896 } 897 898 /** 899 * First, read in the default serializable data. 900 * 901 * Then, if <code>serialVersionOnStream</code> is less than 1, indicating that 902 * the stream was written by JDK 1.1, 903 * set the <code>int</code> fields such as <code>maximumIntegerDigits</code> 904 * to be equal to the <code>byte</code> fields such as <code>maxIntegerDigits</code>, 905 * since the <code>int</code> fields were not present in JDK 1.1. 906 * Finally, set serialVersionOnStream back to the maximum allowed value so that 907 * default serialization will work properly if this object is streamed out again. 908 * 909 * <p>If <code>minimumIntegerDigits</code> is greater than 910 * <code>maximumIntegerDigits</code> or <code>minimumFractionDigits</code> 911 * is greater than <code>maximumFractionDigits</code>, then the stream data 912 * is invalid and this method throws an <code>InvalidObjectException</code>. 913 * In addition, if any of these values is negative, then this method throws 914 * an <code>InvalidObjectException</code>. 915 * 916 * @since 1.2 917 */ 918 private void readObject(ObjectInputStream stream) 919 throws IOException, ClassNotFoundException 920 { 921 stream.defaultReadObject(); 922 if (serialVersionOnStream < 1) { 923 // Didn't have additional int fields, reassign to use them. 924 maximumIntegerDigits = maxIntegerDigits; 925 minimumIntegerDigits = minIntegerDigits; 926 maximumFractionDigits = maxFractionDigits; 927 minimumFractionDigits = minFractionDigits; 928 } 929 if (minimumIntegerDigits > maximumIntegerDigits || 930 minimumFractionDigits > maximumFractionDigits || 931 minimumIntegerDigits < 0 || minimumFractionDigits < 0) { 932 throw new InvalidObjectException("Digit count range invalid"); 933 } 934 serialVersionOnStream = currentSerialVersion; 935 } 936 937 /** 938 * Write out the default serializable data, after first setting 939 * the <code>byte</code> fields such as <code>maxIntegerDigits</code> to be 940 * equal to the <code>int</code> fields such as <code>maximumIntegerDigits</code> 941 * (or to <code>Byte.MAX_VALUE</code>, whichever is smaller), for compatibility 942 * with the JDK 1.1 version of the stream format. 943 * 944 * @since 1.2 945 */ 946 private void writeObject(ObjectOutputStream stream) 947 throws IOException 948 { 949 maxIntegerDigits = (maximumIntegerDigits > Byte.MAX_VALUE) ? 950 Byte.MAX_VALUE : (byte)maximumIntegerDigits; 951 minIntegerDigits = (minimumIntegerDigits > Byte.MAX_VALUE) ? 952 Byte.MAX_VALUE : (byte)minimumIntegerDigits; 953 maxFractionDigits = (maximumFractionDigits > Byte.MAX_VALUE) ? 954 Byte.MAX_VALUE : (byte)maximumFractionDigits; 955 minFractionDigits = (minimumFractionDigits > Byte.MAX_VALUE) ? 956 Byte.MAX_VALUE : (byte)minimumFractionDigits; 957 stream.defaultWriteObject(); 958 } 959 960 // Constants used by factory methods to specify a style of format. 961 private static final int NUMBERSTYLE = 0; 962 private static final int CURRENCYSTYLE = 1; 963 private static final int PERCENTSTYLE = 2; 964 private static final int SCIENTIFICSTYLE = 3; 965 private static final int INTEGERSTYLE = 4; 966 967 /** 968 * True if the grouping (i.e. thousands) separator is used when 969 * formatting and parsing numbers. 970 * 971 * @serial 972 * @see #isGroupingUsed 973 */ 974 private boolean groupingUsed = true; 975 976 /** 977 * The maximum number of digits allowed in the integer portion of a 978 * number. <code>maxIntegerDigits</code> must be greater than or equal to 979 * <code>minIntegerDigits</code>. 980 * <p> 981 * <strong>Note:</strong> This field exists only for serialization 982 * compatibility with JDK 1.1. In Java platform 2 v1.2 and higher, the new 983 * <code>int</code> field <code>maximumIntegerDigits</code> is used instead. 984 * When writing to a stream, <code>maxIntegerDigits</code> is set to 985 * <code>maximumIntegerDigits</code> or <code>Byte.MAX_VALUE</code>, 986 * whichever is smaller. When reading from a stream, this field is used 987 * only if <code>serialVersionOnStream</code> is less than 1. 988 * 989 * @serial 990 * @see #getMaximumIntegerDigits 991 */ 992 private byte maxIntegerDigits = 40; 993 994 /** 995 * The minimum number of digits allowed in the integer portion of a 996 * number. <code>minimumIntegerDigits</code> must be less than or equal to 997 * <code>maximumIntegerDigits</code>. 998 * <p> 999 * <strong>Note:</strong> This field exists only for serialization 1000 * compatibility with JDK 1.1. In Java platform 2 v1.2 and higher, the new 1001 * <code>int</code> field <code>minimumIntegerDigits</code> is used instead. 1002 * When writing to a stream, <code>minIntegerDigits</code> is set to 1003 * <code>minimumIntegerDigits</code> or <code>Byte.MAX_VALUE</code>, 1004 * whichever is smaller. When reading from a stream, this field is used 1005 * only if <code>serialVersionOnStream</code> is less than 1. 1006 * 1007 * @serial 1008 * @see #getMinimumIntegerDigits 1009 */ 1010 private byte minIntegerDigits = 1; 1011 1012 /** 1013 * The maximum number of digits allowed in the fractional portion of a 1014 * number. <code>maximumFractionDigits</code> must be greater than or equal to 1015 * <code>minimumFractionDigits</code>. 1016 * <p> 1017 * <strong>Note:</strong> This field exists only for serialization 1018 * compatibility with JDK 1.1. In Java platform 2 v1.2 and higher, the new 1019 * <code>int</code> field <code>maximumFractionDigits</code> is used instead. 1020 * When writing to a stream, <code>maxFractionDigits</code> is set to 1021 * <code>maximumFractionDigits</code> or <code>Byte.MAX_VALUE</code>, 1022 * whichever is smaller. When reading from a stream, this field is used 1023 * only if <code>serialVersionOnStream</code> is less than 1. 1024 * 1025 * @serial 1026 * @see #getMaximumFractionDigits 1027 */ 1028 private byte maxFractionDigits = 3; // invariant, >= minFractionDigits 1029 1030 /** 1031 * The minimum number of digits allowed in the fractional portion of a 1032 * number. <code>minimumFractionDigits</code> must be less than or equal to 1033 * <code>maximumFractionDigits</code>. 1034 * <p> 1035 * <strong>Note:</strong> This field exists only for serialization 1036 * compatibility with JDK 1.1. In Java platform 2 v1.2 and higher, the new 1037 * <code>int</code> field <code>minimumFractionDigits</code> is used instead. 1038 * When writing to a stream, <code>minFractionDigits</code> is set to 1039 * <code>minimumFractionDigits</code> or <code>Byte.MAX_VALUE</code>, 1040 * whichever is smaller. When reading from a stream, this field is used 1041 * only if <code>serialVersionOnStream</code> is less than 1. 1042 * 1043 * @serial 1044 * @see #getMinimumFractionDigits 1045 */ 1046 private byte minFractionDigits = 0; 1047 1048 /** 1049 * True if this format will parse numbers as integers only. 1050 * 1051 * @serial 1052 * @see #isParseIntegerOnly 1053 */ 1054 private boolean parseIntegerOnly = false; 1055 1056 // new fields for 1.2. byte is too small for integer digits. 1057 1058 /** 1059 * The maximum number of digits allowed in the integer portion of a 1060 * number. <code>maximumIntegerDigits</code> must be greater than or equal to 1061 * <code>minimumIntegerDigits</code>. 1062 * 1063 * @serial 1064 * @since 1.2 1065 * @see #getMaximumIntegerDigits 1066 */ 1067 private int maximumIntegerDigits = 40; 1068 1069 /** 1070 * The minimum number of digits allowed in the integer portion of a 1071 * number. <code>minimumIntegerDigits</code> must be less than or equal to 1072 * <code>maximumIntegerDigits</code>. 1073 * 1074 * @serial 1075 * @since 1.2 1076 * @see #getMinimumIntegerDigits 1077 */ 1078 private int minimumIntegerDigits = 1; 1079 1080 /** 1081 * The maximum number of digits allowed in the fractional portion of a 1082 * number. <code>maximumFractionDigits</code> must be greater than or equal to 1083 * <code>minimumFractionDigits</code>. 1084 * 1085 * @serial 1086 * @since 1.2 1087 * @see #getMaximumFractionDigits 1088 */ 1089 private int maximumFractionDigits = 3; // invariant, >= minFractionDigits 1090 1091 /** 1092 * The minimum number of digits allowed in the fractional portion of a 1093 * number. <code>minimumFractionDigits</code> must be less than or equal to 1094 * <code>maximumFractionDigits</code>. 1095 * 1096 * @serial 1097 * @since 1.2 1098 * @see #getMinimumFractionDigits 1099 */ 1100 private int minimumFractionDigits = 0; 1101 1102 static final int currentSerialVersion = 1; 1103 1104 /** 1105 * Describes the version of <code>NumberFormat</code> present on the stream. 1106 * Possible values are: 1107 * <ul> 1108 * <li><b>0</b> (or uninitialized): the JDK 1.1 version of the stream format. 1109 * In this version, the <code>int</code> fields such as 1110 * <code>maximumIntegerDigits</code> were not present, and the <code>byte</code> 1111 * fields such as <code>maxIntegerDigits</code> are used instead. 1112 * 1113 * <li><b>1</b>: the 1.2 version of the stream format. The values of the 1114 * <code>byte</code> fields such as <code>maxIntegerDigits</code> are ignored, 1115 * and the <code>int</code> fields such as <code>maximumIntegerDigits</code> 1116 * are used instead. 1117 * </ul> 1118 * When streaming out a <code>NumberFormat</code>, the most recent format 1119 * (corresponding to the highest allowable <code>serialVersionOnStream</code>) 1120 * is always written. 1121 * 1122 * @serial 1123 * @since 1.2 1124 */ 1125 private int serialVersionOnStream = currentSerialVersion; 1126 1127 // Removed "implements Cloneable" clause. Needs to update serialization 1128 // ID for backward compatibility. 1129 static final long serialVersionUID = -2308460125733713944L; 1130 1131 1132 // 1133 // class for AttributedCharacterIterator attributes 1134 // 1135 /** 1136 * Defines constants that are used as attribute keys in the 1137 * <code>AttributedCharacterIterator</code> returned 1138 * from <code>NumberFormat.formatToCharacterIterator</code> and as 1139 * field identifiers in <code>FieldPosition</code>. 1140 * 1141 * @since 1.4 1142 */ 1143 public static class Field extends Format.Field { 1144 1145 // Proclaim serial compatibility with 1.4 FCS 1146 private static final long serialVersionUID = 7494728892700160890L; 1147 1148 // table of all instances in this class, used by readResolve 1149 private static final Map<String, Field> instanceMap = new HashMap<>(11); 1150 1151 /** 1152 * Creates a Field instance with the specified 1153 * name. 1154 * 1155 * @param name Name of the attribute 1156 */ 1157 protected Field(String name) { 1158 super(name); 1159 if (this.getClass() == NumberFormat.Field.class) { 1160 instanceMap.put(name, this); 1161 } 1162 } 1163 1164 /** 1165 * Resolves instances being deserialized to the predefined constants. 1166 * 1167 * @throws InvalidObjectException if the constant could not be resolved. 1168 * @return resolved NumberFormat.Field constant 1169 */ 1170 @Override 1171 protected Object readResolve() throws InvalidObjectException { 1172 if (this.getClass() != NumberFormat.Field.class) { 1173 throw new InvalidObjectException("subclass didn't correctly implement readResolve"); 1174 } 1175 1176 Object instance = instanceMap.get(getName()); 1177 if (instance != null) { 1178 return instance; 1179 } else { 1180 throw new InvalidObjectException("unknown attribute name"); 1181 } 1182 } 1183 1184 /** 1185 * Constant identifying the integer field. 1186 */ 1187 public static final Field INTEGER = new Field("integer"); 1188 1189 /** 1190 * Constant identifying the fraction field. 1191 */ 1192 public static final Field FRACTION = new Field("fraction"); 1193 1194 /** 1195 * Constant identifying the exponent field. 1196 */ 1197 public static final Field EXPONENT = new Field("exponent"); 1198 1199 /** 1200 * Constant identifying the decimal separator field. 1201 */ 1202 public static final Field DECIMAL_SEPARATOR = 1203 new Field("decimal separator"); 1204 1205 /** 1206 * Constant identifying the sign field. 1207 */ 1208 public static final Field SIGN = new Field("sign"); 1209 1210 /** 1211 * Constant identifying the grouping separator field. 1212 */ 1213 public static final Field GROUPING_SEPARATOR = 1214 new Field("grouping separator"); 1215 1216 /** 1217 * Constant identifying the exponent symbol field. 1218 */ 1219 public static final Field EXPONENT_SYMBOL = new 1220 Field("exponent symbol"); 1221 1222 /** 1223 * Constant identifying the percent field. 1224 */ 1225 public static final Field PERCENT = new Field("percent"); 1226 1227 /** 1228 * Constant identifying the permille field. 1229 */ 1230 public static final Field PERMILLE = new Field("per mille"); 1231 1232 /** 1233 * Constant identifying the currency field. 1234 */ 1235 public static final Field CURRENCY = new Field("currency"); 1236 1237 /** 1238 * Constant identifying the exponent sign field. 1239 */ 1240 public static final Field EXPONENT_SIGN = new Field("exponent sign"); 1241 } 1242 }