DecimalFormat.java revision 936306df62d7d44a806fbeb789c6432e7c325981
1/* 2 * Licensed to the Apache Software Foundation (ASF) under one or more 3 * contributor license agreements. See the NOTICE file distributed with 4 * this work for additional information regarding copyright ownership. 5 * The ASF licenses this file to You under the Apache License, Version 2.0 6 * (the "License"); you may not use this file except in compliance with 7 * the License. You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 18package java.text; 19 20import java.io.IOException; 21import java.io.ObjectInputStream; 22import java.io.ObjectOutputStream; 23import java.io.ObjectStreamField; 24import java.math.BigDecimal; 25import java.math.BigInteger; 26import java.math.RoundingMode; 27import java.util.Currency; 28import java.util.Locale; 29import libcore.icu.LocaleData; 30import libcore.icu.NativeDecimalFormat; 31 32/** 33 * A concrete subclass of {@link NumberFormat} that formats decimal numbers. It 34 * has a variety of features designed to make it possible to parse and format 35 * numbers in any locale, including support for Western, Arabic, or Indic 36 * digits. It also supports different flavors of numbers, including integers 37 * ("123"), fixed-point numbers ("123.4"), scientific notation ("1.23E4"), 38 * percentages ("12%"), and currency amounts ("$123"). All of these flavors can 39 * be easily localized. 40 * <p> 41 * <strong>This is an enhanced version of {@code DecimalFormat} that is based on 42 * the standard version in the RI. New or changed functionality is labeled 43 * <strong><font color="red">NEW</font></strong>.</strong> 44 * <p> 45 * To obtain a {@link NumberFormat} for a specific locale (including the default 46 * locale), call one of {@code NumberFormat}'s factory methods such as 47 * {@code NumberFormat.getInstance}. Do not call the {@code DecimalFormat} 48 * constructors directly, unless you know what you are doing, since the 49 * {@link NumberFormat} factory methods may return subclasses other than 50 * {@code DecimalFormat}. If you need to customize the format object, do 51 * something like this: <blockquote> 52 * 53 * <pre> 54 * NumberFormat f = NumberFormat.getInstance(loc); 55 * if (f instanceof DecimalFormat) { 56 * ((DecimalFormat)f).setDecimalSeparatorAlwaysShown(true); 57 * } 58 * </pre> 59 * 60 * </blockquote> 61 * 62 * <h4>Patterns</h4> 63 * <p> 64 * A {@code DecimalFormat} consists of a <em>pattern</em> and a set of 65 * <em>symbols</em>. The pattern may be set directly using 66 * {@link #applyPattern(String)}, or indirectly using other API methods which 67 * manipulate aspects of the pattern, such as the minimum number of integer 68 * digits. The symbols are stored in a {@link DecimalFormatSymbols} object. When 69 * using the {@link NumberFormat} factory methods, the pattern and symbols are 70 * read from ICU's locale data. 71 * <h4>Special Pattern Characters</h4> 72 * <p> 73 * Many characters in a pattern are taken literally; they are matched during 74 * parsing and are written out unchanged during formatting. On the other hand, 75 * special characters stand for other characters, strings, or classes of 76 * characters. For example, the '#' character is replaced by a localized digit. 77 * Often the replacement character is the same as the pattern character; in the 78 * U.S. locale, the ',' grouping character is replaced by ','. However, the 79 * replacement is still happening, and if the symbols are modified, the grouping 80 * character changes. Some special characters affect the behavior of the 81 * formatter by their presence; for example, if the percent character is seen, 82 * then the value is multiplied by 100 before being displayed. 83 * <p> 84 * To insert a special character in a pattern as a literal, that is, without any 85 * special meaning, the character must be quoted. There are some exceptions to 86 * this which are noted below. 87 * <p> 88 * The characters listed here are used in non-localized patterns. Localized 89 * patterns use the corresponding characters taken from this formatter's 90 * {@link DecimalFormatSymbols} object instead, and these characters lose their 91 * special status. Two exceptions are the currency sign and quote, which are not 92 * localized. 93 * <blockquote> <table border="0" cellspacing="3" cellpadding="0" summary="Chart 94 * showing symbol, location, localized, and meaning."> 95 * <tr bgcolor="#ccccff"> 96 * <th align="left">Symbol</th> 97 * <th align="left">Location</th> 98 * <th align="left">Localized?</th> 99 * <th align="left">Meaning</th> 100 * </tr> 101 * <tr valign="top"> 102 * <td>{@code 0}</td> 103 * <td>Number</td> 104 * <td>Yes</td> 105 * <td>Digit.</td> 106 * </tr> 107 * <tr valign="top"> 108 * <td>{@code @}</td> 109 * <td>Number</td> 110 * <td>No</td> 111 * <td><strong><font color="red">NEW</font> </strong> Significant 112 * digit.</td> 113 * </tr> 114 * <tr valign="top" bgcolor="#eeeeff"> 115 * <td>{@code #}</td> 116 * <td>Number</td> 117 * <td>Yes</td> 118 * <td>Digit, leading zeroes are not shown.</td> 119 * </tr> 120 * <tr valign="top"> 121 * <td>{@code .}</td> 122 * <td>Number</td> 123 * <td>Yes</td> 124 * <td>Decimal separator or monetary decimal separator.</td> 125 * </tr> 126 * <tr valign="top" bgcolor="#eeeeff"> 127 * <td>{@code -}</td> 128 * <td>Number</td> 129 * <td>Yes</td> 130 * <td>Minus sign.</td> 131 * </tr> 132 * <tr valign="top"> 133 * <td>{@code ,}</td> 134 * <td>Number</td> 135 * <td>Yes</td> 136 * <td>Grouping separator.</td> 137 * </tr> 138 * <tr valign="top" bgcolor="#eeeeff"> 139 * <td>{@code E}</td> 140 * <td>Number</td> 141 * <td>Yes</td> 142 * <td>Separates mantissa and exponent in scientific notation. 143 * <em>Does not need to be quoted in prefix or suffix.</em></td> 144 * </tr> 145 * <tr valign="top"> 146 * <td>{@code +}</td> 147 * <td>Exponent</td> 148 * <td>Yes</td> 149 * <td><strong><font color="red">NEW</font> </strong> Prefix 150 * positive exponents with localized plus sign. 151 * <em>Does not need to be quoted in prefix or suffix.</em></td> 152 * </tr> 153 * <tr valign="top" bgcolor="#eeeeff"> 154 * <td>{@code ;}</td> 155 * <td>Subpattern boundary</td> 156 * <td>Yes</td> 157 * <td>Separates positive and negative subpatterns.</td> 158 * </tr> 159 * <tr valign="top"> 160 * <td>{@code %}</td> 161 * <td>Prefix or suffix</td> 162 * <td>Yes</td> 163 * <td>Multiply by 100 and show as percentage.</td> 164 * </tr> 165 * <tr valign="top" bgcolor="#eeeeff"> 166 * <td>{@code \u2030} ({@code \u005Cu2030})</td> 167 * <td>Prefix or suffix</td> 168 * <td>Yes</td> 169 * <td>Multiply by 1000 and show as per mille.</td> 170 * </tr> 171 * <tr valign="top"> 172 * <td>{@code \u00A4} ({@code \u005Cu00A4})</td> 173 * <td>Prefix or suffix</td> 174 * <td>No</td> 175 * <td>Currency sign, replaced by currency symbol. If doubled, replaced by 176 * international currency symbol. If present in a pattern, the monetary decimal 177 * separator is used instead of the decimal separator.</td> 178 * </tr> 179 * <tr valign="top" bgcolor="#eeeeff"> 180 * <td>{@code '}</td> 181 * <td>Prefix or suffix</td> 182 * <td>No</td> 183 * <td>Used to quote special characters in a prefix or suffix, for example, 184 * {@code "'#'#"} formats 123 to {@code "#123"}. To create a single quote 185 * itself, use two in a row: {@code "# o''clock"}.</td> 186 * </tr> 187 * <tr valign="top"> 188 * <td>{@code *}</td> 189 * <td>Prefix or suffix boundary</td> 190 * <td>Yes</td> 191 * <td><strong><font color="red">NEW</font> </strong> Pad escape, 192 * precedes pad character. </td> 193 * </tr> 194 * </table> </blockquote> 195 * <p> 196 * A {@code DecimalFormat} pattern contains a positive and negative subpattern, 197 * for example, "#,##0.00;(#,##0.00)". Each subpattern has a prefix, a numeric 198 * part and a suffix. If there is no explicit negative subpattern, the negative 199 * subpattern is the localized minus sign prefixed to the positive subpattern. 200 * That is, "0.00" alone is equivalent to "0.00;-0.00". If there is an explicit 201 * negative subpattern, it serves only to specify the negative prefix and 202 * suffix; the number of digits, minimal digits, and other characteristics are 203 * ignored in the negative subpattern. This means that "#,##0.0#;(#)" produces 204 * precisely the same result as "#,##0.0#;(#,##0.0#)". 205 * <p> 206 * The prefixes, suffixes, and various symbols used for infinity, digits, 207 * thousands separators, decimal separators, etc. may be set to arbitrary 208 * values, and they will appear properly during formatting. However, care must 209 * be taken that the symbols and strings do not conflict, or parsing will be 210 * unreliable. For example, either the positive and negative prefixes or the 211 * suffixes must be distinct for {@link #parse} to be able to distinguish 212 * positive from negative values. Another example is that the decimal separator 213 * and thousands separator should be distinct characters, or parsing will be 214 * impossible. 215 * <p> 216 * The <em>grouping separator</em> is a character that separates clusters of 217 * integer digits to make large numbers more legible. It is commonly used for 218 * thousands, but in some locales it separates ten-thousands. The <em>grouping 219 * size</em> 220 * is the number of digits between the grouping separators, such as 3 for 221 * "100,000,000" or 4 for "1 0000 0000". There are actually two different 222 * grouping sizes: One used for the least significant integer digits, the 223 * <em>primary grouping size</em>, and one used for all others, the 224 * <em>secondary grouping size</em>. In most locales these are the same, but 225 * sometimes they are different. For example, if the primary grouping interval 226 * is 3, and the secondary is 2, then this corresponds to the pattern 227 * "#,##,##0", and the number 123456789 is formatted as "12,34,56,789". If a 228 * pattern contains multiple grouping separators, the interval between the last 229 * one and the end of the integer defines the primary grouping size, and the 230 * interval between the last two defines the secondary grouping size. All others 231 * are ignored, so "#,##,###,####", "###,###,####" and "##,#,###,####" produce 232 * the same result. 233 * <p> 234 * Illegal patterns, such as "#.#.#" or "#.###,###", will cause 235 * {@code DecimalFormat} to throw an {@link IllegalArgumentException} with a 236 * message that describes the problem. 237 * <h4>Pattern BNF</h4> 238 * 239 * <pre> 240 * pattern := subpattern (';' subpattern)? 241 * subpattern := prefix? number exponent? suffix? 242 * number := (integer ('.' fraction)?) | sigDigits 243 * prefix := '\\u0000'..'\\uFFFD' - specialCharacters 244 * suffix := '\\u0000'..'\\uFFFD' - specialCharacters 245 * integer := '#'* '0'* '0' 246 * fraction := '0'* '#'* 247 * sigDigits := '#'* '@' '@'* '#'* 248 * exponent := 'E' '+'? '0'* '0' 249 * padSpec := '*' padChar 250 * padChar := '\\u0000'..'\\uFFFD' - quote 251 * 252 * Notation: 253 * X* 0 or more instances of X 254 * X? 0 or 1 instances of X 255 * X|Y either X or Y 256 * C..D any character from C up to D, inclusive 257 * S-T characters in S, except those in T 258 * </pre> 259 * 260 * The first subpattern is for positive numbers. The second (optional) 261 * subpattern is for negative numbers. 262 * <p> 263 * Not indicated in the BNF syntax above: 264 * <ul> 265 * <li>The grouping separator ',' can occur inside the integer and sigDigits 266 * elements, between any two pattern characters of that element, as long as the 267 * integer or sigDigits element is not followed by the exponent element. 268 * <li><font color="red"><strong>NEW</strong> </font> Two 269 * grouping intervals are recognized: The one between the decimal point and the 270 * first grouping symbol and the one between the first and second grouping 271 * symbols. These intervals are identical in most locales, but in some locales 272 * they differ. For example, the pattern "#,##,###" formats the number 273 * 123456789 as "12,34,56,789".</li> 274 * <li> <strong><font color="red">NEW</font> </strong> The pad 275 * specifier {@code padSpec} may appear before the prefix, after the prefix, 276 * before the suffix, after the suffix or not at all. 277 * </ul> 278 * <h4>Parsing</h4> 279 * <p> 280 * {@code DecimalFormat} parses all Unicode characters that represent decimal 281 * digits, as defined by {@link Character#digit(int, int)}. In addition, 282 * {@code DecimalFormat} also recognizes as digits the ten consecutive 283 * characters starting with the localized zero digit defined in the 284 * {@link DecimalFormatSymbols} object. During formatting, the 285 * {@link DecimalFormatSymbols}-based digits are written out. 286 * <p> 287 * During parsing, grouping separators are ignored. 288 * <p> 289 * If {@link #parse(String, ParsePosition)} fails to parse a string, it returns 290 * {@code null} and leaves the parse position unchanged. 291 * <h4>Formatting</h4> 292 * <p> 293 * Formatting is guided by several parameters, all of which can be specified 294 * either using a pattern or using the API. The following description applies to 295 * formats that do not use <a href="#sci">scientific notation</a> or <a 296 * href="#sigdig">significant digits</a>. 297 * <ul> 298 * <li>If the number of actual integer digits exceeds the 299 * <em>maximum integer digits</em>, then only the least significant digits 300 * are shown. For example, 1997 is formatted as "97" if maximum integer digits 301 * is set to 2. 302 * <li>If the number of actual integer digits is less than the 303 * <em>minimum integer digits</em>, then leading zeros are added. For 304 * example, 1997 is formatted as "01997" if minimum integer digits is set to 5. 305 * <li>If the number of actual fraction digits exceeds the <em>maximum 306 * fraction digits</em>, 307 * then half-even rounding is performed to the maximum fraction digits. For 308 * example, 0.125 is formatted as "0.12" if the maximum fraction digits is 2. 309 * <li>If the number of actual fraction digits is less than the 310 * <em>minimum fraction digits</em>, then trailing zeros are added. For 311 * example, 0.125 is formatted as "0.1250" if the minimum fraction digits is set 312 * to 4. 313 * <li>Trailing fractional zeros are not displayed if they occur <em>j</em> 314 * positions after the decimal, where <em>j</em> is less than the maximum 315 * fraction digits. For example, 0.10004 is formatted as "0.1" if the maximum 316 * fraction digits is four or less. 317 * </ul> 318 * <p> 319 * <strong>Special Values</strong> 320 * <p> 321 * {@code NaN} is represented as a single character, typically 322 * {@code \u005cuFFFD}. This character is determined by the 323 * {@link DecimalFormatSymbols} object. This is the only value for which the 324 * prefixes and suffixes are not used. 325 * <p> 326 * Infinity is represented as a single character, typically {@code \u005cu221E}, 327 * with the positive or negative prefixes and suffixes applied. The infinity 328 * character is determined by the {@link DecimalFormatSymbols} object. <a 329 * name="sci"> 330 * <h4>Scientific Notation</h4> 331 * </a> 332 * <p> 333 * Numbers in scientific notation are expressed as the product of a mantissa and 334 * a power of ten, for example, 1234 can be expressed as 1.234 x 10<sup>3</sup>. 335 * The mantissa is typically in the half-open interval [1.0, 10.0) or sometimes 336 * [0.0, 1.0), but it does not need to be. {@code DecimalFormat} supports 337 * arbitrary mantissas. {@code DecimalFormat} can be instructed to use 338 * scientific notation through the API or through the pattern. In a pattern, the 339 * exponent character immediately followed by one or more digit characters 340 * indicates scientific notation. Example: "0.###E0" formats the number 1234 as 341 * "1.234E3". 342 * <ul> 343 * <li>The number of digit characters after the exponent character gives the 344 * minimum exponent digit count. There is no maximum. Negative exponents are 345 * formatted using the localized minus sign, <em>not</em> the prefix and 346 * suffix from the pattern. This allows patterns such as "0.###E0 m/s". To 347 * prefix positive exponents with a localized plus sign, specify '+' between the 348 * exponent and the digits: "0.###E+0" will produce formats "1E+1", "1E+0", 349 * "1E-1", etc. (In localized patterns, use the localized plus sign rather than 350 * '+'.) 351 * <li>The minimum number of integer digits is achieved by adjusting the 352 * exponent. Example: 0.00123 formatted with "00.###E0" yields "12.3E-4". This 353 * only happens if there is no maximum number of integer digits. If there is a 354 * maximum, then the minimum number of integer digits is fixed at one. 355 * <li>The maximum number of integer digits, if present, specifies the exponent 356 * grouping. The most common use of this is to generate <em>engineering 357 * notation</em>, 358 * in which the exponent is a multiple of three, e.g., "##0.###E0". The number 359 * 12345 is formatted using "##0.###E0" as "12.345E3". 360 * <li>When using scientific notation, the formatter controls the digit counts 361 * using significant digits logic. The maximum number of significant digits 362 * limits the total number of integer and fraction digits that will be shown in 363 * the mantissa; it does not affect parsing. For example, 12345 formatted with 364 * "##0.##E0" is "12.3E3". See the section on significant digits for more 365 * details. 366 * <li>The number of significant digits shown is determined as follows: If no 367 * significant digits are used in the pattern then the minimum number of 368 * significant digits shown is one, the maximum number of significant digits 369 * shown is the sum of the <em>minimum integer</em> and 370 * <em>maximum fraction</em> digits, and it is unaffected by the maximum 371 * integer digits. If this sum is zero, then all significant digits are shown. 372 * If significant digits are used in the pattern then the number of integer 373 * digits is fixed at one and there is no exponent grouping. 374 * <li>Exponential patterns may not contain grouping separators. 375 * </ul> 376 * <a name="sigdig"></a> 377 * <h4> <strong><font color="red">NEW</font> </strong> Significant 378 * Digits</h4> 379 * <p> 380 * {@code DecimalFormat} has two ways of controlling how many digits are 381 * shown: (a) significant digit counts or (b) integer and fraction digit counts. 382 * Integer and fraction digit counts are described above. When a formatter uses 383 * significant digits counts, the number of integer and fraction digits is not 384 * specified directly, and the formatter settings for these counts are ignored. 385 * Instead, the formatter uses as many integer and fraction digits as required 386 * to display the specified number of significant digits. 387 * <h5>Examples:</h5> 388 * <blockquote> <table border=0 cellspacing=3 cellpadding=0> 389 * <tr bgcolor="#ccccff"> 390 * <th align="left">Pattern</th> 391 * <th align="left">Minimum significant digits</th> 392 * <th align="left">Maximum significant digits</th> 393 * <th align="left">Number</th> 394 * <th align="left">Output of format()</th> 395 * </tr> 396 * <tr valign="top"> 397 * <td>{@code @@@} 398 * <td>3</td> 399 * <td>3</td> 400 * <td>12345</td> 401 * <td>{@code 12300}</td> 402 * </tr> 403 * <tr valign="top" bgcolor="#eeeeff"> 404 * <td>{@code @@@}</td> 405 * <td>3</td> 406 * <td>3</td> 407 * <td>0.12345</td> 408 * <td>{@code 0.123}</td> 409 * </tr> 410 * <tr valign="top"> 411 * <td>{@code @@##}</td> 412 * <td>2</td> 413 * <td>4</td> 414 * <td>3.14159</td> 415 * <td>{@code 3.142}</td> 416 * </tr> 417 * <tr valign="top" bgcolor="#eeeeff"> 418 * <td>{@code @@##}</td> 419 * <td>2</td> 420 * <td>4</td> 421 * <td>1.23004</td> 422 * <td>{@code 1.23}</td> 423 * </tr> 424 * </table> </blockquote> 425 * <ul> 426 * <li>Significant digit counts may be expressed using patterns that specify a 427 * minimum and maximum number of significant digits. These are indicated by the 428 * {@code '@'} and {@code '#'} characters. The minimum number of significant 429 * digits is the number of {@code '@'} characters. The maximum number of 430 * significant digits is the number of {@code '@'} characters plus the number of 431 * {@code '#'} characters following on the right. For example, the pattern 432 * {@code "@@@"} indicates exactly 3 significant digits. The pattern 433 * {@code "@##"} indicates from 1 to 3 significant digits. Trailing zero digits 434 * to the right of the decimal separator are suppressed after the minimum number 435 * of significant digits have been shown. For example, the pattern {@code "@##"} 436 * formats the number 0.1203 as {@code "0.12"}. 437 * <li>If a pattern uses significant digits, it may not contain a decimal 438 * separator, nor the {@code '0'} pattern character. Patterns such as 439 * {@code "@00"} or {@code "@.###"} are disallowed. 440 * <li>Any number of {@code '#'} characters may be prepended to the left of the 441 * leftmost {@code '@'} character. These have no effect on the minimum and 442 * maximum significant digit counts, but may be used to position grouping 443 * separators. For example, {@code "#,#@#"} indicates a minimum of one 444 * significant digit, a maximum of two significant digits, and a grouping size 445 * of three. 446 * <li>In order to enable significant digits formatting, use a pattern 447 * containing the {@code '@'} pattern character. 448 * <li>In order to disable significant digits formatting, use a pattern that 449 * does not contain the {@code '@'} pattern character. 450 * <li>The number of significant digits has no effect on parsing. 451 * <li>Significant digits may be used together with exponential notation. Such 452 * patterns are equivalent to a normal exponential pattern with a minimum and 453 * maximum integer digit count of one, a minimum fraction digit count of the 454 * number of '@' characters in the pattern - 1, and a maximum fraction digit 455 * count of the number of '@' and '#' characters in the pattern - 1. For 456 * example, the pattern {@code "@@###E0"} is equivalent to {@code "0.0###E0"}. 457 * <li>If significant digits are in use then the integer and fraction digit 458 * counts, as set via the API, are ignored. 459 * </ul> 460 * <h4> <strong><font color="red">NEW</font> </strong> Padding</h4> 461 * <p> 462 * {@code DecimalFormat} supports padding the result of {@code format} to a 463 * specific width. Padding may be specified either through the API or through 464 * the pattern syntax. In a pattern, the pad escape character followed by a 465 * single pad character causes padding to be parsed and formatted. The pad 466 * escape character is '*' in unlocalized patterns. For example, 467 * {@code "$*x#,##0.00"} formats 123 to {@code "$xx123.00"}, and 1234 to 468 * {@code "$1,234.00"}. 469 * <ul> 470 * <li>When padding is in effect, the width of the positive subpattern, 471 * including prefix and suffix, determines the format width. For example, in the 472 * pattern {@code "* #0 o''clock"}, the format width is 10.</li> 473 * <li>The width is counted in 16-bit code units (Java {@code char}s).</li> 474 * <li>Some parameters which usually do not matter have meaning when padding is 475 * used, because the pattern width is significant with padding. In the pattern "* 476 * ##,##,#,##0.##", the format width is 14. The initial characters "##,##," do 477 * not affect the grouping size or maximum integer digits, but they do affect 478 * the format width.</li> 479 * <li>Padding may be inserted at one of four locations: before the prefix, 480 * after the prefix, before the suffix or after the suffix. If padding is 481 * specified in any other location, {@link #applyPattern} throws an {@link 482 * IllegalArgumentException}. If there is no prefix, before the prefix and after 483 * the prefix are equivalent, likewise for the suffix.</li> 484 * <li>When specified in a pattern, the 16-bit {@code char} immediately 485 * following the pad escape is the pad character. This may be any character, 486 * including a special pattern character. That is, the pad escape 487 * <em>escapes</em> the following character. If there is no character after 488 * the pad escape, then the pattern is illegal.</li> 489 * </ul> 490 * 491 * <h4>Serialization</h4> 492 * <p> 493 * Features marked as <strong><font color="red">NEW</font></strong> and patterns that use 494 * characters not documented above are unlikely to serialize/deserialize correctly. 495 * 496 * <h4>Synchronization</h4> 497 * <p> 498 * {@code DecimalFormat} objects are not synchronized. Multiple threads should 499 * not access one formatter concurrently. 500 * 501 * @see Format 502 * @see NumberFormat 503 */ 504public class DecimalFormat extends NumberFormat { 505 506 private static final long serialVersionUID = 864413376551465018L; 507 508 private transient DecimalFormatSymbols symbols; 509 510 private transient NativeDecimalFormat ndf; 511 512 private transient RoundingMode roundingMode = RoundingMode.HALF_EVEN; 513 514 /** 515 * Constructs a new {@code DecimalFormat} for formatting and parsing numbers 516 * for the user's default locale. 517 * See "<a href="../util/Locale.html#default_locale">Be wary of the default locale</a>". 518 */ 519 public DecimalFormat() { 520 Locale locale = Locale.getDefault(); 521 this.symbols = new DecimalFormatSymbols(locale); 522 initNative(LocaleData.get(locale).numberPattern); 523 } 524 525 /** 526 * Constructs a new {@code DecimalFormat} using the specified non-localized 527 * pattern and the {@code DecimalFormatSymbols} for the user's default Locale. 528 * See "<a href="../util/Locale.html#default_locale">Be wary of the default locale</a>". 529 * @param pattern 530 * the non-localized pattern. 531 * @throws IllegalArgumentException 532 * if the pattern cannot be parsed. 533 */ 534 public DecimalFormat(String pattern) { 535 this(pattern, Locale.getDefault()); 536 } 537 538 /** 539 * Constructs a new {@code DecimalFormat} using the specified non-localized 540 * pattern and {@code DecimalFormatSymbols}. 541 * 542 * @param pattern 543 * the non-localized pattern. 544 * @param value 545 * the DecimalFormatSymbols. 546 * @throws IllegalArgumentException 547 * if the pattern cannot be parsed. 548 */ 549 public DecimalFormat(String pattern, DecimalFormatSymbols value) { 550 this.symbols = (DecimalFormatSymbols) value.clone(); 551 initNative(pattern); 552 } 553 554 // Used by NumberFormat.getInstance because cloning DecimalFormatSymbols is slow. 555 DecimalFormat(String pattern, Locale locale) { 556 this.symbols = new DecimalFormatSymbols(locale); 557 initNative(pattern); 558 } 559 560 private void initNative(String pattern) { 561 try { 562 this.ndf = new NativeDecimalFormat(pattern, symbols); 563 } catch (IllegalArgumentException ex) { 564 throw new IllegalArgumentException(pattern); 565 } 566 super.setMaximumFractionDigits(ndf.getMaximumFractionDigits()); 567 super.setMaximumIntegerDigits(ndf.getMaximumIntegerDigits()); 568 super.setMinimumFractionDigits(ndf.getMinimumFractionDigits()); 569 super.setMinimumIntegerDigits(ndf.getMinimumIntegerDigits()); 570 } 571 572 /** 573 * Changes the pattern of this decimal format to the specified pattern which 574 * uses localized pattern characters. 575 * 576 * @param pattern 577 * the localized pattern. 578 * @throws IllegalArgumentException 579 * if the pattern cannot be parsed. 580 */ 581 public void applyLocalizedPattern(String pattern) { 582 ndf.applyLocalizedPattern(pattern); 583 updateFieldsFromNative(); 584 } 585 586 /** 587 * Changes the pattern of this decimal format to the specified pattern which 588 * uses non-localized pattern characters. 589 * 590 * @param pattern 591 * the non-localized pattern. 592 * @throws IllegalArgumentException 593 * if the pattern cannot be parsed. 594 */ 595 public void applyPattern(String pattern) { 596 // The underlying ICU4C accepts a super-set of the pattern spec documented by the Android 597 // APIs. For example, rounding increments (pattern characters '1'-'9'). They will work but 598 // see class doc for issues with serialization/deserialization they may cause. 599 ndf.applyPattern(pattern); 600 updateFieldsFromNative(); 601 } 602 603 private void updateFieldsFromNative() { 604 maximumIntegerDigits = ndf.getMaximumIntegerDigits(); 605 minimumIntegerDigits = ndf.getMinimumIntegerDigits(); 606 maximumFractionDigits = ndf.getMaximumFractionDigits(); 607 minimumFractionDigits = ndf.getMinimumFractionDigits(); 608 } 609 610 /** 611 * Returns a new instance of {@code DecimalFormat} with the same pattern and 612 * properties. 613 */ 614 @Override 615 public Object clone() { 616 DecimalFormat clone = (DecimalFormat) super.clone(); 617 clone.ndf = (NativeDecimalFormat) ndf.clone(); 618 clone.symbols = (DecimalFormatSymbols) symbols.clone(); 619 return clone; 620 } 621 622 /** 623 * Compares the specified object to this decimal format and indicates if 624 * they are equal. In order to be equal, {@code object} must be an instance 625 * of {@code DecimalFormat} with the same pattern and properties. 626 * 627 * @param object 628 * the object to compare with this object. 629 * @return {@code true} if the specified object is equal to this decimal 630 * format; {@code false} otherwise. 631 * @see #hashCode 632 */ 633 @Override 634 public boolean equals(Object object) { 635 if (this == object) { 636 return true; 637 } 638 if (!(object instanceof DecimalFormat)) { 639 return false; 640 } 641 DecimalFormat other = (DecimalFormat) object; 642 return (this.ndf == null ? other.ndf == null : this.ndf.equals(other.ndf)) && 643 getDecimalFormatSymbols().equals(other.getDecimalFormatSymbols()); 644 } 645 646 /** 647 * Formats the specified object using the rules of this decimal format and 648 * returns an {@code AttributedCharacterIterator} with the formatted number 649 * and attributes. 650 * 651 * @param object 652 * the object to format. 653 * @return an AttributedCharacterIterator with the formatted number and 654 * attributes. 655 * @throws IllegalArgumentException 656 * if {@code object} cannot be formatted by this format. 657 * @throws NullPointerException 658 * if {@code object} is {@code null}. 659 */ 660 @Override 661 public AttributedCharacterIterator formatToCharacterIterator(Object object) { 662 if (object == null) { 663 throw new NullPointerException("object == null"); 664 } 665 return ndf.formatToCharacterIterator(object); 666 } 667 668 private void checkBufferAndFieldPosition(StringBuffer buffer, FieldPosition position) { 669 if (buffer == null) { 670 throw new NullPointerException("buffer == null"); 671 } 672 if (position == null) { 673 throw new NullPointerException("position == null"); 674 } 675 } 676 677 @Override 678 public StringBuffer format(double value, StringBuffer buffer, FieldPosition position) { 679 checkBufferAndFieldPosition(buffer, position); 680 buffer.append(ndf.formatDouble(value, position)); 681 return buffer; 682 } 683 684 @Override 685 public StringBuffer format(long value, StringBuffer buffer, FieldPosition position) { 686 checkBufferAndFieldPosition(buffer, position); 687 buffer.append(ndf.formatLong(value, position)); 688 return buffer; 689 } 690 691 @Override 692 public final StringBuffer format(Object number, StringBuffer buffer, FieldPosition position) { 693 checkBufferAndFieldPosition(buffer, position); 694 if (number instanceof BigInteger) { 695 BigInteger bigInteger = (BigInteger) number; 696 char[] chars = (bigInteger.bitLength() < 64) 697 ? ndf.formatLong(bigInteger.longValue(), position) 698 : ndf.formatBigInteger(bigInteger, position); 699 buffer.append(chars); 700 return buffer; 701 } else if (number instanceof BigDecimal) { 702 buffer.append(ndf.formatBigDecimal((BigDecimal) number, position)); 703 return buffer; 704 } 705 return super.format(number, buffer, position); 706 } 707 708 /** 709 * Returns the {@code DecimalFormatSymbols} used by this decimal format. 710 * 711 * @return a copy of the {@code DecimalFormatSymbols} used by this decimal 712 * format. 713 */ 714 public DecimalFormatSymbols getDecimalFormatSymbols() { 715 return (DecimalFormatSymbols) symbols.clone(); 716 } 717 718 /** 719 * Returns the currency used by this decimal format. 720 * 721 * @return the currency used by this decimal format. 722 * @see DecimalFormatSymbols#getCurrency() 723 */ 724 @Override 725 public Currency getCurrency() { 726 return symbols.getCurrency(); 727 } 728 729 /** 730 * Returns the number of digits grouped together by the grouping separator. 731 * This only allows to get the primary grouping size. There is no API to get 732 * the secondary grouping size. 733 * 734 * @return the number of digits grouped together. 735 */ 736 public int getGroupingSize() { 737 return ndf.getGroupingSize(); 738 } 739 740 /** 741 * Returns the prefix which is formatted or parsed before a negative number. 742 * 743 * @return the negative prefix. 744 */ 745 public String getNegativePrefix() { 746 return ndf.getNegativePrefix(); 747 } 748 749 /** 750 * Returns the suffix which is formatted or parsed after a negative number. 751 * 752 * @return the negative suffix. 753 */ 754 public String getNegativeSuffix() { 755 return ndf.getNegativeSuffix(); 756 } 757 758 /** 759 * Returns the prefix which is formatted or parsed before a positive number. 760 * 761 * @return the positive prefix. 762 */ 763 public String getPositivePrefix() { 764 return ndf.getPositivePrefix(); 765 } 766 767 /** 768 * Returns the suffix which is formatted or parsed after a positive number. 769 * 770 * @return the positive suffix. 771 */ 772 public String getPositiveSuffix() { 773 return ndf.getPositiveSuffix(); 774 } 775 776 @Override 777 public int hashCode() { 778 return getPositivePrefix().hashCode(); 779 } 780 781 /** 782 * Indicates whether the decimal separator is shown when there are no 783 * fractional digits. 784 * 785 * @return {@code true} if the decimal separator should always be formatted; 786 * {@code false} otherwise. 787 */ 788 public boolean isDecimalSeparatorAlwaysShown() { 789 return ndf.isDecimalSeparatorAlwaysShown(); 790 } 791 792 /** 793 * This value indicates whether the return object of the parse operation is 794 * of type {@code BigDecimal}. This value defaults to {@code false}. 795 * 796 * @return {@code true} if parse always returns {@code BigDecimals}, 797 * {@code false} if the type of the result is {@code Long} or 798 * {@code Double}. 799 */ 800 public boolean isParseBigDecimal() { 801 return ndf.isParseBigDecimal(); 802 } 803 804 /** 805 * Sets the flag that indicates whether numbers will be parsed as integers. 806 * When this decimal format is used for parsing and this value is set to 807 * {@code true}, then the resulting numbers will be of type 808 * {@code java.lang.Integer}. Special cases are NaN, positive and negative 809 * infinity, which are still returned as {@code java.lang.Double}. 810 * 811 * 812 * @param value 813 * {@code true} that the resulting numbers of parse operations 814 * will be of type {@code java.lang.Integer} except for the 815 * special cases described above. 816 */ 817 @Override 818 public void setParseIntegerOnly(boolean value) { 819 // In this implementation, NativeDecimalFormat is wrapped to 820 // fulfill most of the format and parse feature. And this method is 821 // delegated to the wrapped instance of NativeDecimalFormat. 822 super.setParseIntegerOnly(value); 823 ndf.setParseIntegerOnly(value); 824 } 825 826 @Override 827 public boolean isParseIntegerOnly() { 828 return ndf.isParseIntegerOnly(); 829 } 830 831 private static final Double NEGATIVE_ZERO_DOUBLE = new Double(-0.0); 832 833 /** 834 * Parses a {@code Long} or {@code Double} from the specified string 835 * starting at the index specified by {@code position}. If the string is 836 * successfully parsed then the index of the {@code ParsePosition} is 837 * updated to the index following the parsed text. On error, the index is 838 * unchanged and the error index of {@code ParsePosition} is set to the 839 * index where the error occurred. 840 * 841 * @param string 842 * the string to parse. 843 * @param position 844 * input/output parameter, specifies the start index in 845 * {@code string} from where to start parsing. If parsing is 846 * successful, it is updated with the index following the parsed 847 * text; on error, the index is unchanged and the error index is 848 * set to the index where the error occurred. 849 * @return a {@code Long} or {@code Double} resulting from the parse or 850 * {@code null} if there is an error. The result will be a 851 * {@code Long} if the parsed number is an integer in the range of a 852 * long, otherwise the result is a {@code Double}. If 853 * {@code isParseBigDecimal} is {@code true} then it returns the 854 * result as a {@code BigDecimal}. 855 */ 856 @Override 857 public Number parse(String string, ParsePosition position) { 858 Number number = ndf.parse(string, position); 859 if (number == null) { 860 return null; 861 } 862 if (this.isParseBigDecimal()) { 863 if (number instanceof Long) { 864 return new BigDecimal(number.longValue()); 865 } 866 if ((number instanceof Double) && !((Double) number).isInfinite() 867 && !((Double) number).isNaN()) { 868 869 return new BigDecimal(number.toString()); 870 } 871 if (number instanceof BigInteger) { 872 return new BigDecimal(number.toString()); 873 } 874 return number; 875 } 876 if ((number instanceof BigDecimal) || (number instanceof BigInteger)) { 877 return new Double(number.doubleValue()); 878 } 879 if (this.isParseIntegerOnly() && number.equals(NEGATIVE_ZERO_DOUBLE)) { 880 return Long.valueOf(0); 881 } 882 return number; 883 884 } 885 886 /** 887 * Sets the {@code DecimalFormatSymbols} used by this decimal format. 888 */ 889 public void setDecimalFormatSymbols(DecimalFormatSymbols value) { 890 if (value != null) { 891 // The Java object is canonical, and we copy down to native code. 892 this.symbols = (DecimalFormatSymbols) value.clone(); 893 ndf.setDecimalFormatSymbols(this.symbols); 894 } 895 } 896 897 /** 898 * Sets the currency used by this decimal format. The min and max fraction 899 * digits remain the same. 900 */ 901 @Override 902 public void setCurrency(Currency currency) { 903 Currency instance = Currency.getInstance(currency.getCurrencyCode()); 904 symbols.setCurrency(instance); 905 ndf.setCurrency(symbols.getCurrencySymbol(), currency.getCurrencyCode()); 906 } 907 908 /** 909 * Sets whether the decimal separator is shown even when there are no fractional 910 * digits. 911 */ 912 public void setDecimalSeparatorAlwaysShown(boolean value) { 913 ndf.setDecimalSeparatorAlwaysShown(value); 914 } 915 916 /** 917 * Sets the number of digits grouped together by the grouping separator. 918 * This only allows to set the primary grouping size; the secondary grouping 919 * size can only be set with a pattern. 920 */ 921 public void setGroupingSize(int value) { 922 ndf.setGroupingSize(value); 923 } 924 925 /** 926 * Sets whether or not digit grouping will be used in this format. Grouping 927 * affects both formatting and parsing. 928 */ 929 @Override 930 public void setGroupingUsed(boolean value) { 931 ndf.setGroupingUsed(value); 932 } 933 934 /** 935 * Returns true if digit grouping is used in this format. Grouping affects both 936 * formatting and parsing. 937 */ 938 @Override 939 public boolean isGroupingUsed() { 940 return ndf.isGroupingUsed(); 941 } 942 943 /** 944 * Sets the maximum number of digits after the decimal point. 945 * If the value passed is negative then it is replaced by 0. 946 * Regardless of this setting, no more than 340 digits will be used. 947 */ 948 @Override 949 public void setMaximumFractionDigits(int value) { 950 super.setMaximumFractionDigits(value); 951 ndf.setMaximumFractionDigits(getMaximumFractionDigits()); 952 // Changing the maximum fraction digits needs to update ICU4C's rounding configuration. 953 setRoundingMode(roundingMode); 954 } 955 956 /** 957 * Sets the maximum number of digits before the decimal point. 958 * If the value passed is negative then it is replaced by 0. 959 * Regardless of this setting, no more than 309 digits will be used. 960 */ 961 @Override 962 public void setMaximumIntegerDigits(int value) { 963 super.setMaximumIntegerDigits(value); 964 ndf.setMaximumIntegerDigits(getMaximumIntegerDigits()); 965 } 966 967 /** 968 * Sets the minimum number of digits after the decimal point. 969 * If the value passed is negative then it is replaced by 0. 970 * Regardless of this setting, no more than 340 digits will be used. 971 */ 972 @Override 973 public void setMinimumFractionDigits(int value) { 974 super.setMinimumFractionDigits(value); 975 ndf.setMinimumFractionDigits(getMinimumFractionDigits()); 976 } 977 978 /** 979 * Sets the minimum number of digits before the decimal point. 980 * If the value passed is negative then it is replaced by 0. 981 * Regardless of this setting, no more than 309 digits will be used. 982 */ 983 @Override 984 public void setMinimumIntegerDigits(int value) { 985 super.setMinimumIntegerDigits(value); 986 ndf.setMinimumIntegerDigits(getMinimumIntegerDigits()); 987 } 988 989 /** 990 * Returns the multiplier which is applied to the number before formatting 991 * or after parsing. The multiplier is meant for tasks like parsing percentages. 992 * For example, given a multiplier of 100, 1.23 would be formatted as "123" and 993 * "123" would be parsed as 1.23. 994 */ 995 public int getMultiplier() { 996 return ndf.getMultiplier(); 997 } 998 999 /** 1000 * Sets the multiplier which is applied to the number before formatting or 1001 * after parsing. The multiplier meant for tasks like parsing percentages. 1002 * For example, given a multiplier of 100, 1.23 would be formatted as "123" and 1003 * "123" would be parsed as 1.23. 1004 */ 1005 public void setMultiplier(int value) { 1006 ndf.setMultiplier(value); 1007 } 1008 1009 /** 1010 * Sets the prefix which is formatted or parsed before a negative number. 1011 */ 1012 public void setNegativePrefix(String value) { 1013 ndf.setNegativePrefix(value); 1014 } 1015 1016 /** 1017 * Sets the suffix which is formatted or parsed after a negative number. 1018 */ 1019 public void setNegativeSuffix(String value) { 1020 ndf.setNegativeSuffix(value); 1021 } 1022 1023 /** 1024 * Sets the prefix which is formatted or parsed before a positive number. 1025 */ 1026 public void setPositivePrefix(String value) { 1027 ndf.setPositivePrefix(value); 1028 } 1029 1030 /** 1031 * Sets the suffix which is formatted or parsed after a positive number. 1032 */ 1033 public void setPositiveSuffix(String value) { 1034 ndf.setPositiveSuffix(value); 1035 } 1036 1037 /** 1038 * Sets the behavior of the parse method. If set to {@code true} then all 1039 * the returned objects will be of type {@code BigDecimal}. 1040 * 1041 * @param newValue 1042 * {@code true} if all the returned objects should be of type 1043 * {@code BigDecimal}; {@code false} otherwise. 1044 */ 1045 public void setParseBigDecimal(boolean newValue) { 1046 ndf.setParseBigDecimal(newValue); 1047 } 1048 1049 /** 1050 * Returns the pattern of this decimal format using localized pattern 1051 * characters. 1052 * 1053 * @return the localized pattern. 1054 */ 1055 public String toLocalizedPattern() { 1056 return ndf.toLocalizedPattern(); 1057 } 1058 1059 /** 1060 * Returns the pattern of this decimal format using non-localized pattern 1061 * characters. 1062 * 1063 * @return the non-localized pattern. 1064 */ 1065 public String toPattern() { 1066 return ndf.toPattern(); 1067 } 1068 1069 // the fields list to be serialized 1070 private static final ObjectStreamField[] serialPersistentFields = { 1071 new ObjectStreamField("positivePrefix", String.class), 1072 new ObjectStreamField("positiveSuffix", String.class), 1073 new ObjectStreamField("negativePrefix", String.class), 1074 new ObjectStreamField("negativeSuffix", String.class), 1075 new ObjectStreamField("posPrefixPattern", String.class), 1076 new ObjectStreamField("posSuffixPattern", String.class), 1077 new ObjectStreamField("negPrefixPattern", String.class), 1078 new ObjectStreamField("negSuffixPattern", String.class), 1079 new ObjectStreamField("multiplier", int.class), 1080 new ObjectStreamField("groupingSize", byte.class), 1081 new ObjectStreamField("groupingUsed", boolean.class), 1082 new ObjectStreamField("decimalSeparatorAlwaysShown", boolean.class), 1083 new ObjectStreamField("parseBigDecimal", boolean.class), 1084 new ObjectStreamField("roundingMode", RoundingMode.class), 1085 new ObjectStreamField("symbols", DecimalFormatSymbols.class), 1086 new ObjectStreamField("useExponentialNotation", boolean.class), 1087 new ObjectStreamField("minExponentDigits", byte.class), 1088 new ObjectStreamField("maximumIntegerDigits", int.class), 1089 new ObjectStreamField("minimumIntegerDigits", int.class), 1090 new ObjectStreamField("maximumFractionDigits", int.class), 1091 new ObjectStreamField("minimumFractionDigits", int.class), 1092 new ObjectStreamField("serialVersionOnStream", int.class), 1093 }; 1094 1095 /** 1096 * Writes serialized fields following serialized forms specified by Java 1097 * specification. 1098 * 1099 * @param stream 1100 * the output stream to write serialized bytes 1101 * @throws IOException 1102 * if some I/O error occurs 1103 * @throws ClassNotFoundException 1104 */ 1105 private void writeObject(ObjectOutputStream stream) throws IOException, ClassNotFoundException { 1106 ObjectOutputStream.PutField fields = stream.putFields(); 1107 fields.put("positivePrefix", ndf.getPositivePrefix()); 1108 fields.put("positiveSuffix", ndf.getPositiveSuffix()); 1109 fields.put("negativePrefix", ndf.getNegativePrefix()); 1110 fields.put("negativeSuffix", ndf.getNegativeSuffix()); 1111 fields.put("posPrefixPattern", (String) null); 1112 fields.put("posSuffixPattern", (String) null); 1113 fields.put("negPrefixPattern", (String) null); 1114 fields.put("negSuffixPattern", (String) null); 1115 fields.put("multiplier", ndf.getMultiplier()); 1116 fields.put("groupingSize", (byte) ndf.getGroupingSize()); 1117 fields.put("groupingUsed", ndf.isGroupingUsed()); 1118 fields.put("decimalSeparatorAlwaysShown", ndf.isDecimalSeparatorAlwaysShown()); 1119 fields.put("parseBigDecimal", ndf.isParseBigDecimal()); 1120 fields.put("roundingMode", roundingMode); 1121 fields.put("symbols", symbols); 1122 fields.put("useExponentialNotation", false); 1123 fields.put("minExponentDigits", (byte) 0); 1124 fields.put("maximumIntegerDigits", ndf.getMaximumIntegerDigits()); 1125 fields.put("minimumIntegerDigits", ndf.getMinimumIntegerDigits()); 1126 fields.put("maximumFractionDigits", ndf.getMaximumFractionDigits()); 1127 fields.put("minimumFractionDigits", ndf.getMinimumFractionDigits()); 1128 fields.put("serialVersionOnStream", 4); 1129 stream.writeFields(); 1130 } 1131 1132 /** 1133 * Reads serialized fields following serialized forms specified by Java 1134 * specification. 1135 * 1136 * @param stream 1137 * the input stream to read serialized bytes 1138 * @throws IOException 1139 * if some I/O error occurs 1140 * @throws ClassNotFoundException 1141 * if some class of serialized objects or fields cannot be found 1142 */ 1143 private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { 1144 ObjectInputStream.GetField fields = stream.readFields(); 1145 this.symbols = (DecimalFormatSymbols) fields.get("symbols", null); 1146 1147 initNative(""); 1148 ndf.setPositivePrefix((String) fields.get("positivePrefix", "")); 1149 ndf.setPositiveSuffix((String) fields.get("positiveSuffix", "")); 1150 ndf.setNegativePrefix((String) fields.get("negativePrefix", "-")); 1151 ndf.setNegativeSuffix((String) fields.get("negativeSuffix", "")); 1152 ndf.setMultiplier(fields.get("multiplier", 1)); 1153 ndf.setGroupingSize(fields.get("groupingSize", (byte) 3)); 1154 ndf.setGroupingUsed(fields.get("groupingUsed", true)); 1155 ndf.setDecimalSeparatorAlwaysShown(fields.get("decimalSeparatorAlwaysShown", false)); 1156 1157 setRoundingMode((RoundingMode) fields.get("roundingMode", RoundingMode.HALF_EVEN)); 1158 1159 final int maximumIntegerDigits = fields.get("maximumIntegerDigits", 309); 1160 final int minimumIntegerDigits = fields.get("minimumIntegerDigits", 309); 1161 final int maximumFractionDigits = fields.get("maximumFractionDigits", 340); 1162 final int minimumFractionDigits = fields.get("minimumFractionDigits", 340); 1163 // Tell ICU what we want, then ask it what we can have, and then 1164 // set that in our Java object. This isn't RI-compatible, but then very little of our 1165 // behavior in this area is, and it's not obvious how we can second-guess ICU (or tell 1166 // it to just do exactly what we ask). We only need to do this with maximumIntegerDigits 1167 // because ICU doesn't seem to have its own ideas about the other options. 1168 ndf.setMaximumIntegerDigits(maximumIntegerDigits); 1169 super.setMaximumIntegerDigits(ndf.getMaximumIntegerDigits()); 1170 1171 setMinimumIntegerDigits(minimumIntegerDigits); 1172 setMinimumFractionDigits(minimumFractionDigits); 1173 setMaximumFractionDigits(maximumFractionDigits); 1174 setParseBigDecimal(fields.get("parseBigDecimal", false)); 1175 1176 if (fields.get("serialVersionOnStream", 0) < 3) { 1177 setMaximumIntegerDigits(super.getMaximumIntegerDigits()); 1178 setMinimumIntegerDigits(super.getMinimumIntegerDigits()); 1179 setMaximumFractionDigits(super.getMaximumFractionDigits()); 1180 setMinimumFractionDigits(super.getMinimumFractionDigits()); 1181 } 1182 } 1183 1184 /** 1185 * Returns the {@code RoundingMode} used by this {@code NumberFormat}. 1186 * @since 1.6 1187 */ 1188 public RoundingMode getRoundingMode() { 1189 return roundingMode; 1190 } 1191 1192 /** 1193 * Sets the {@code RoundingMode} used by this {@code NumberFormat}. 1194 * @since 1.6 1195 */ 1196 public void setRoundingMode(RoundingMode roundingMode) { 1197 if (roundingMode == null) { 1198 throw new NullPointerException("roundingMode == null"); 1199 } 1200 this.roundingMode = roundingMode; 1201 // DecimalFormat does not allow specification of a rounding increment. If anything other 1202 // than 0.0 is used here the resulting DecimalFormat cannot be deserialized because the 1203 // serialization format does not include rounding increment information. 1204 double roundingIncrement = 0.0; 1205 ndf.setRoundingMode(roundingMode, roundingIncrement); 1206 } 1207 1208 public String toString() { return ndf.toString(); } 1209} 1210