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