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