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