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