DecimalFormat.java revision b46dab348e2007bc08abaf7ecae34d89a2474e50
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"> 377 * <h4> <strong><font color="red">NEW</font> </strong> Significant 378 * Digits</h4> 379 * <p> 380 * </a> {@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 * <h4>Synchronization</h4> 491 * <p> 492 * {@code DecimalFormat} objects are not synchronized. Multiple threads should 493 * not access one formatter concurrently. 494 * 495 * @see Format 496 * @see NumberFormat 497 */ 498public class DecimalFormat extends NumberFormat { 499 500 private static final long serialVersionUID = 864413376551465018L; 501 502 private transient DecimalFormatSymbols symbols; 503 504 private transient NativeDecimalFormat dform; 505 private final Object finalizerGuardian = new Object() { 506 @Override protected void finalize() throws Throwable { 507 try { 508 dform.close(); 509 } finally { 510 super.finalize(); 511 } 512 } 513 }; 514 515 private transient RoundingMode roundingMode = RoundingMode.HALF_EVEN; 516 517 /** 518 * Constructs a new {@code DecimalFormat} for formatting and parsing numbers 519 * for the user's default locale. 520 * See "<a href="../util/Locale.html#default_locale">Be wary of the default locale</a>". 521 */ 522 public DecimalFormat() { 523 Locale locale = Locale.getDefault(); 524 this.symbols = new DecimalFormatSymbols(locale); 525 initNative(LocaleData.get(locale).numberPattern); 526 } 527 528 /** 529 * Constructs a new {@code DecimalFormat} using the specified non-localized 530 * pattern and the {@code DecimalFormatSymbols} for the user's default Locale. 531 * See "<a href="../util/Locale.html#default_locale">Be wary of the default locale</a>". 532 * @param pattern 533 * the non-localized pattern. 534 * @throws IllegalArgumentException 535 * if the pattern cannot be parsed. 536 */ 537 public DecimalFormat(String pattern) { 538 this(pattern, Locale.getDefault()); 539 } 540 541 /** 542 * Constructs a new {@code DecimalFormat} using the specified non-localized 543 * pattern and {@code DecimalFormatSymbols}. 544 * 545 * @param pattern 546 * the non-localized pattern. 547 * @param value 548 * the DecimalFormatSymbols. 549 * @throws IllegalArgumentException 550 * if the pattern cannot be parsed. 551 */ 552 public DecimalFormat(String pattern, DecimalFormatSymbols value) { 553 this.symbols = (DecimalFormatSymbols) value.clone(); 554 initNative(pattern); 555 } 556 557 // Used by NumberFormat.getInstance because cloning DecimalFormatSymbols is slow. 558 DecimalFormat(String pattern, Locale locale) { 559 this.symbols = new DecimalFormatSymbols(locale); 560 initNative(pattern); 561 } 562 563 private void initNative(String pattern) { 564 try { 565 this.dform = new NativeDecimalFormat(pattern, symbols); 566 } catch (IllegalArgumentException ex) { 567 throw new IllegalArgumentException(pattern); 568 } 569 super.setMaximumFractionDigits(dform.getMaximumFractionDigits()); 570 super.setMaximumIntegerDigits(dform.getMaximumIntegerDigits()); 571 super.setMinimumFractionDigits(dform.getMinimumFractionDigits()); 572 super.setMinimumIntegerDigits(dform.getMinimumIntegerDigits()); 573 } 574 575 /** 576 * Changes the pattern of this decimal format to the specified pattern which 577 * uses localized pattern characters. 578 * 579 * @param pattern 580 * the localized pattern. 581 * @throws IllegalArgumentException 582 * if the pattern cannot be parsed. 583 */ 584 public void applyLocalizedPattern(String pattern) { 585 dform.applyLocalizedPattern(pattern); 586 } 587 588 /** 589 * Changes the pattern of this decimal format to the specified pattern which 590 * uses non-localized pattern characters. 591 * 592 * @param pattern 593 * the non-localized pattern. 594 * @throws IllegalArgumentException 595 * if the pattern cannot be parsed. 596 */ 597 public void applyPattern(String pattern) { 598 dform.applyPattern(pattern); 599 } 600 601 /** 602 * Returns a new instance of {@code DecimalFormat} with the same pattern and 603 * properties as this decimal format. 604 * 605 * @return a shallow copy of this decimal format. 606 * @see java.lang.Cloneable 607 */ 608 @Override 609 public Object clone() { 610 DecimalFormat clone = (DecimalFormat) super.clone(); 611 clone.dform = (NativeDecimalFormat) dform.clone(); 612 clone.symbols = (DecimalFormatSymbols) symbols.clone(); 613 return clone; 614 } 615 616 /** 617 * Compares the specified object to this decimal format and indicates if 618 * they are equal. In order to be equal, {@code object} must be an instance 619 * of {@code DecimalFormat} with the same pattern and properties. 620 * 621 * @param object 622 * the object to compare with this object. 623 * @return {@code true} if the specified object is equal to this decimal 624 * format; {@code false} otherwise. 625 * @see #hashCode 626 */ 627 @Override 628 public boolean equals(Object object) { 629 if (this == object) { 630 return true; 631 } 632 if (!(object instanceof DecimalFormat)) { 633 return false; 634 } 635 DecimalFormat other = (DecimalFormat) object; 636 return (this.dform == null ? other.dform == null : this.dform.equals(other.dform)) && 637 getDecimalFormatSymbols().equals(other.getDecimalFormatSymbols()); 638 } 639 640 /** 641 * Formats the specified object using the rules of this decimal format and 642 * returns an {@code AttributedCharacterIterator} with the formatted number 643 * and attributes. 644 * 645 * @param object 646 * the object to format. 647 * @return an AttributedCharacterIterator with the formatted number and 648 * attributes. 649 * @throws IllegalArgumentException 650 * if {@code object} cannot be formatted by this format. 651 * @throws NullPointerException 652 * if {@code object} is {@code null}. 653 */ 654 @Override 655 public AttributedCharacterIterator formatToCharacterIterator(Object object) { 656 if (object == null) { 657 throw new NullPointerException(); 658 } 659 return dform.formatToCharacterIterator(object); 660 } 661 662 private void checkBufferAndFieldPosition(StringBuffer buffer, FieldPosition position) { 663 if (buffer == null) { 664 throw new NullPointerException("buffer == null"); 665 } 666 if (position == null) { 667 throw new NullPointerException("position == null"); 668 } 669 } 670 671 @Override 672 public StringBuffer format(double value, StringBuffer buffer, FieldPosition position) { 673 checkBufferAndFieldPosition(buffer, position); 674 // All float/double/Float/Double formatting ends up here... 675 if (roundingMode == RoundingMode.UNNECESSARY) { 676 // ICU4C doesn't support this rounding mode, so we have to fake it. 677 try { 678 setRoundingMode(RoundingMode.UP); 679 String upResult = format(value, new StringBuffer(), new FieldPosition(0)).toString(); 680 setRoundingMode(RoundingMode.DOWN); 681 String downResult = format(value, new StringBuffer(), new FieldPosition(0)).toString(); 682 if (!upResult.equals(downResult)) { 683 throw new ArithmeticException("rounding mode UNNECESSARY but rounding required"); 684 } 685 } finally { 686 setRoundingMode(RoundingMode.UNNECESSARY); 687 } 688 } 689 buffer.append(dform.formatDouble(value, position)); 690 return buffer; 691 } 692 693 @Override 694 public StringBuffer format(long value, StringBuffer buffer, FieldPosition position) { 695 checkBufferAndFieldPosition(buffer, position); 696 buffer.append(dform.formatLong(value, position)); 697 return buffer; 698 } 699 700 @Override 701 public final StringBuffer format(Object number, StringBuffer buffer, FieldPosition position) { 702 checkBufferAndFieldPosition(buffer, position); 703 if (number instanceof BigInteger) { 704 BigInteger bigInteger = (BigInteger) number; 705 char[] chars = (bigInteger.bitLength() < 64) 706 ? dform.formatLong(bigInteger.longValue(), position) 707 : dform.formatBigInteger(bigInteger, position); 708 buffer.append(chars); 709 return buffer; 710 } else if (number instanceof BigDecimal) { 711 buffer.append(dform.formatBigDecimal((BigDecimal) number, position)); 712 return buffer; 713 } 714 return super.format(number, buffer, position); 715 } 716 717 /** 718 * Returns the {@code DecimalFormatSymbols} used by this decimal format. 719 * 720 * @return a copy of the {@code DecimalFormatSymbols} used by this decimal 721 * format. 722 */ 723 public DecimalFormatSymbols getDecimalFormatSymbols() { 724 return (DecimalFormatSymbols) symbols.clone(); 725 } 726 727 /** 728 * Returns the currency used by this decimal format. 729 * 730 * @return the currency used by this decimal format. 731 * @see DecimalFormatSymbols#getCurrency() 732 */ 733 @Override 734 public Currency getCurrency() { 735 return symbols.getCurrency(); 736 } 737 738 /** 739 * Returns the number of digits grouped together by the grouping separator. 740 * This only allows to get the primary grouping size. There is no API to get 741 * the secondary grouping size. 742 * 743 * @return the number of digits grouped together. 744 */ 745 public int getGroupingSize() { 746 return dform.getGroupingSize(); 747 } 748 749 /** 750 * Returns the multiplier which is applied to the number before formatting 751 * or after parsing. 752 * 753 * @return the multiplier. 754 */ 755 public int getMultiplier() { 756 return dform.getMultiplier(); 757 } 758 759 /** 760 * Returns the prefix which is formatted or parsed before a negative number. 761 * 762 * @return the negative prefix. 763 */ 764 public String getNegativePrefix() { 765 return dform.getNegativePrefix(); 766 } 767 768 /** 769 * Returns the suffix which is formatted or parsed after a negative number. 770 * 771 * @return the negative suffix. 772 */ 773 public String getNegativeSuffix() { 774 return dform.getNegativeSuffix(); 775 } 776 777 /** 778 * Returns the prefix which is formatted or parsed before a positive number. 779 * 780 * @return the positive prefix. 781 */ 782 public String getPositivePrefix() { 783 return dform.getPositivePrefix(); 784 } 785 786 /** 787 * Returns the suffix which is formatted or parsed after a positive number. 788 * 789 * @return the positive suffix. 790 */ 791 public String getPositiveSuffix() { 792 return dform.getPositiveSuffix(); 793 } 794 795 @Override 796 public int hashCode() { 797 return dform.hashCode(); 798 } 799 800 /** 801 * Indicates whether the decimal separator is shown when there are no 802 * fractional digits. 803 * 804 * @return {@code true} if the decimal separator should always be formatted; 805 * {@code false} otherwise. 806 */ 807 public boolean isDecimalSeparatorAlwaysShown() { 808 return dform.isDecimalSeparatorAlwaysShown(); 809 } 810 811 /** 812 * This value indicates whether the return object of the parse operation is 813 * of type {@code BigDecimal}. This value defaults to {@code false}. 814 * 815 * @return {@code true} if parse always returns {@code BigDecimals}, 816 * {@code false} if the type of the result is {@code Long} or 817 * {@code Double}. 818 */ 819 public boolean isParseBigDecimal() { 820 return dform.isParseBigDecimal(); 821 } 822 823 /** 824 * Sets the flag that indicates whether numbers will be parsed as integers. 825 * When this decimal format is used for parsing and this value is set to 826 * {@code true}, then the resulting numbers will be of type 827 * {@code java.lang.Integer}. Special cases are NaN, positive and negative 828 * infinity, which are still returned as {@code java.lang.Double}. 829 * 830 * 831 * @param value 832 * {@code true} that the resulting numbers of parse operations 833 * will be of type {@code java.lang.Integer} except for the 834 * special cases described above. 835 */ 836 @Override 837 public void setParseIntegerOnly(boolean value) { 838 // In this implementation, NativeDecimalFormat is wrapped to 839 // fulfill most of the format and parse feature. And this method is 840 // delegated to the wrapped instance of NativeDecimalFormat. 841 dform.setParseIntegerOnly(value); 842 } 843 844 /** 845 * Indicates whether parsing with this decimal format will only 846 * return numbers of type {@code java.lang.Integer}. 847 * 848 * @return {@code true} if this {@code DecimalFormat}'s parse method only 849 * returns {@code java.lang.Integer}; {@code false} otherwise. 850 */ 851 @Override 852 public boolean isParseIntegerOnly() { 853 return dform.isParseIntegerOnly(); 854 } 855 856 private static final Double NEGATIVE_ZERO_DOUBLE = new Double(-0.0); 857 858 /** 859 * Parses a {@code Long} or {@code Double} from the specified string 860 * starting at the index specified by {@code position}. If the string is 861 * successfully parsed then the index of the {@code ParsePosition} is 862 * updated to the index following the parsed text. On error, the index is 863 * unchanged and the error index of {@code ParsePosition} is set to the 864 * index where the error occurred. 865 * 866 * @param string 867 * the string to parse. 868 * @param position 869 * input/output parameter, specifies the start index in 870 * {@code string} from where to start parsing. If parsing is 871 * successful, it is updated with the index following the parsed 872 * text; on error, the index is unchanged and the error index is 873 * set to the index where the error occurred. 874 * @return a {@code Long} or {@code Double} resulting from the parse or 875 * {@code null} if there is an error. The result will be a 876 * {@code Long} if the parsed number is an integer in the range of a 877 * long, otherwise the result is a {@code Double}. If 878 * {@code isParseBigDecimal} is {@code true} then it returns the 879 * result as a {@code BigDecimal}. 880 */ 881 @Override 882 public Number parse(String string, ParsePosition position) { 883 Number number = dform.parse(string, position); 884 if (number == null) { 885 return null; 886 } 887 // BEGIN android-removed 888 // if (this.isParseBigDecimal()) { 889 // if (number instanceof Long) { 890 // return new BigDecimal(number.longValue()); 891 // } 892 // if ((number instanceof Double) && !((Double) number).isInfinite() 893 // && !((Double) number).isNaN()) { 894 // 895 // return new BigDecimal(number.doubleValue()); 896 // } 897 // if (number instanceof BigInteger) { 898 // return new BigDecimal(number.doubleValue()); 899 // } 900 // if (number instanceof com.ibm.icu.math.BigDecimal) { 901 // return new BigDecimal(number.toString()); 902 // } 903 // return number; 904 // } 905 // if ((number instanceof com.ibm.icu.math.BigDecimal) 906 // || (number instanceof BigInteger)) { 907 // return new Double(number.doubleValue()); 908 // } 909 // END android-removed 910 // BEGIN android-added 911 if (this.isParseBigDecimal()) { 912 if (number instanceof Long) { 913 return new BigDecimal(number.longValue()); 914 } 915 if ((number instanceof Double) && !((Double) number).isInfinite() 916 && !((Double) number).isNaN()) { 917 918 return new BigDecimal(number.toString()); 919 } 920 if (number instanceof BigInteger) { 921 return new BigDecimal(number.toString()); 922 } 923 return number; 924 } 925 if ((number instanceof BigDecimal) || (number instanceof BigInteger)) { 926 return new Double(number.doubleValue()); 927 } 928 // END android-added 929 930 if (this.isParseIntegerOnly() && number.equals(NEGATIVE_ZERO_DOUBLE)) { 931 return Long.valueOf(0); // android-changed 932 } 933 return number; 934 935 } 936 937 /** 938 * Sets the {@code DecimalFormatSymbols} used by this decimal format. 939 * 940 * @param value 941 * the {@code DecimalFormatSymbols} to set. 942 */ 943 public void setDecimalFormatSymbols(DecimalFormatSymbols value) { 944 if (value != null) { 945 // BEGIN android-changed: the Java object is canonical, and we copy down to native code. 946 this.symbols = (DecimalFormatSymbols) value.clone(); 947 dform.setDecimalFormatSymbols(this.symbols); 948 // END android-changed 949 } 950 } 951 952 /** 953 * Sets the currency used by this decimal format. The min and max fraction 954 * digits remain the same. 955 * 956 * @param currency 957 * the currency this {@code DecimalFormat} should use. 958 * @see DecimalFormatSymbols#setCurrency(Currency) 959 */ 960 @Override 961 public void setCurrency(Currency currency) { 962 // BEGIN android-changed 963 dform.setCurrency(Currency.getInstance(currency.getCurrencyCode())); 964 // END android-changed 965 symbols.setCurrency(currency); 966 } 967 968 /** 969 * Sets whether the decimal separator is shown when there are no fractional 970 * digits. 971 * 972 * @param value 973 * {@code true} if the decimal separator should always be 974 * formatted; {@code false} otherwise. 975 */ 976 public void setDecimalSeparatorAlwaysShown(boolean value) { 977 dform.setDecimalSeparatorAlwaysShown(value); 978 } 979 980 /** 981 * Sets the number of digits grouped together by the grouping separator. 982 * This only allows to set the primary grouping size; the secondary grouping 983 * size can only be set with a pattern. 984 * 985 * @param value 986 * the number of digits grouped together. 987 */ 988 public void setGroupingSize(int value) { 989 dform.setGroupingSize(value); 990 } 991 992 /** 993 * Sets whether or not grouping will be used in this format. Grouping 994 * affects both parsing and formatting. 995 * 996 * @param value 997 * {@code true} if grouping is used; {@code false} otherwise. 998 */ 999 @Override 1000 public void setGroupingUsed(boolean value) { 1001 dform.setGroupingUsed(value); 1002 } 1003 1004 /** 1005 * Indicates whether grouping will be used in this format. 1006 * 1007 * @return {@code true} if grouping is used; {@code false} otherwise. 1008 */ 1009 @Override 1010 public boolean isGroupingUsed() { 1011 return dform.isGroupingUsed(); 1012 } 1013 1014 /** 1015 * Sets the maximum number of digits after the decimal point. 1016 * If the value passed is negative then it is replaced by 0. 1017 * Regardless of this setting, no more than 340 digits will be used. 1018 * 1019 * @param value the maximum number of fraction digits. 1020 */ 1021 @Override 1022 public void setMaximumFractionDigits(int value) { 1023 super.setMaximumFractionDigits(value); 1024 dform.setMaximumFractionDigits(getMaximumFractionDigits()); 1025 // Changing the maximum fraction digits needs to update ICU4C's rounding configuration. 1026 setRoundingMode(roundingMode); 1027 } 1028 1029 /** 1030 * Sets the maximum number of digits before the decimal point. 1031 * If the value passed is negative then it is replaced by 0. 1032 * Regardless of this setting, no more than 309 digits will be used. 1033 * 1034 * @param value the maximum number of integer digits. 1035 */ 1036 @Override 1037 public void setMaximumIntegerDigits(int value) { 1038 super.setMaximumIntegerDigits(value); 1039 dform.setMaximumIntegerDigits(getMaximumIntegerDigits()); 1040 } 1041 1042 /** 1043 * Sets the minimum number of digits after the decimal point. 1044 * If the value passed is negative then it is replaced by 0. 1045 * Regardless of this setting, no more than 340 digits will be used. 1046 * 1047 * @param value the minimum number of fraction digits. 1048 */ 1049 @Override 1050 public void setMinimumFractionDigits(int value) { 1051 super.setMinimumFractionDigits(value); 1052 dform.setMinimumFractionDigits(getMinimumFractionDigits()); 1053 } 1054 1055 /** 1056 * Sets the minimum number of digits before the decimal point. 1057 * If the value passed is negative then it is replaced by 0. 1058 * Regardless of this setting, no more than 309 digits will be used. 1059 * 1060 * @param value the minimum number of integer digits. 1061 */ 1062 @Override 1063 public void setMinimumIntegerDigits(int value) { 1064 super.setMinimumIntegerDigits(value); 1065 dform.setMinimumIntegerDigits(getMinimumIntegerDigits()); 1066 } 1067 1068 /** 1069 * Sets the multiplier which is applied to the number before formatting or 1070 * after parsing. 1071 * 1072 * @param value 1073 * the multiplier. 1074 */ 1075 public void setMultiplier(int value) { 1076 dform.setMultiplier(value); 1077 } 1078 1079 /** 1080 * Sets the prefix which is formatted or parsed before a negative number. 1081 * 1082 * @param value 1083 * the negative prefix. 1084 */ 1085 public void setNegativePrefix(String value) { 1086 dform.setNegativePrefix(value); 1087 } 1088 1089 /** 1090 * Sets the suffix which is formatted or parsed after a negative number. 1091 * 1092 * @param value 1093 * the negative suffix. 1094 */ 1095 public void setNegativeSuffix(String value) { 1096 dform.setNegativeSuffix(value); 1097 } 1098 1099 /** 1100 * Sets the prefix which is formatted or parsed before a positive number. 1101 * 1102 * @param value 1103 * the positive prefix. 1104 */ 1105 public void setPositivePrefix(String value) { 1106 dform.setPositivePrefix(value); 1107 } 1108 1109 /** 1110 * Sets the suffix which is formatted or parsed after a positive number. 1111 * 1112 * @param value 1113 * the positive suffix. 1114 */ 1115 public void setPositiveSuffix(String value) { 1116 dform.setPositiveSuffix(value); 1117 } 1118 1119 /** 1120 * Sets the behavior of the parse method. If set to {@code true} then all 1121 * the returned objects will be of type {@code BigDecimal}. 1122 * 1123 * @param newValue 1124 * {@code true} if all the returned objects should be of type 1125 * {@code BigDecimal}; {@code false} otherwise. 1126 */ 1127 public void setParseBigDecimal(boolean newValue) { 1128 dform.setParseBigDecimal(newValue); 1129 } 1130 1131 /** 1132 * Returns the pattern of this decimal format using localized pattern 1133 * characters. 1134 * 1135 * @return the localized pattern. 1136 */ 1137 public String toLocalizedPattern() { 1138 return dform.toLocalizedPattern(); 1139 } 1140 1141 /** 1142 * Returns the pattern of this decimal format using non-localized pattern 1143 * characters. 1144 * 1145 * @return the non-localized pattern. 1146 */ 1147 public String toPattern() { 1148 return dform.toPattern(); 1149 } 1150 1151 // the fields list to be serialized 1152 private static final ObjectStreamField[] serialPersistentFields = { 1153 new ObjectStreamField("positivePrefix", String.class), 1154 new ObjectStreamField("positiveSuffix", String.class), 1155 new ObjectStreamField("negativePrefix", String.class), 1156 new ObjectStreamField("negativeSuffix", String.class), 1157 new ObjectStreamField("posPrefixPattern", String.class), 1158 new ObjectStreamField("posSuffixPattern", String.class), 1159 new ObjectStreamField("negPrefixPattern", String.class), 1160 new ObjectStreamField("negSuffixPattern", String.class), 1161 new ObjectStreamField("multiplier", int.class), 1162 new ObjectStreamField("groupingSize", byte.class), 1163 new ObjectStreamField("groupingUsed", boolean.class), 1164 new ObjectStreamField("decimalSeparatorAlwaysShown", boolean.class), 1165 new ObjectStreamField("parseBigDecimal", boolean.class), 1166 new ObjectStreamField("roundingMode", RoundingMode.class), 1167 new ObjectStreamField("symbols", DecimalFormatSymbols.class), 1168 new ObjectStreamField("useExponentialNotation", boolean.class), 1169 new ObjectStreamField("minExponentDigits", byte.class), 1170 new ObjectStreamField("maximumIntegerDigits", int.class), 1171 new ObjectStreamField("minimumIntegerDigits", int.class), 1172 new ObjectStreamField("maximumFractionDigits", int.class), 1173 new ObjectStreamField("minimumFractionDigits", int.class), 1174 new ObjectStreamField("serialVersionOnStream", int.class), }; 1175 1176 /** 1177 * Writes serialized fields following serialized forms specified by Java 1178 * specification. 1179 * 1180 * @param stream 1181 * the output stream to write serialized bytes 1182 * @throws IOException 1183 * if some I/O error occurs 1184 * @throws ClassNotFoundException 1185 */ 1186 @SuppressWarnings("nls") 1187 private void writeObject(ObjectOutputStream stream) throws IOException, 1188 ClassNotFoundException { 1189 ObjectOutputStream.PutField fields = stream.putFields(); 1190 fields.put("positivePrefix", dform.getPositivePrefix()); 1191 fields.put("positiveSuffix", dform.getPositiveSuffix()); 1192 fields.put("negativePrefix", dform.getNegativePrefix()); 1193 fields.put("negativeSuffix", dform.getNegativeSuffix()); 1194 fields.put("posPrefixPattern", (String) null); 1195 fields.put("posSuffixPattern", (String) null); 1196 fields.put("negPrefixPattern", (String) null); 1197 fields.put("negSuffixPattern", (String) null); 1198 fields.put("multiplier", dform.getMultiplier()); 1199 fields.put("groupingSize", (byte) dform.getGroupingSize()); 1200 // BEGIN android-added 1201 fields.put("groupingUsed", dform.isGroupingUsed()); 1202 // END android-added 1203 fields.put("decimalSeparatorAlwaysShown", dform 1204 .isDecimalSeparatorAlwaysShown()); 1205 fields.put("parseBigDecimal", dform.isParseBigDecimal()); 1206 fields.put("roundingMode", roundingMode); 1207 fields.put("symbols", symbols); 1208 fields.put("useExponentialNotation", false); 1209 fields.put("minExponentDigits", (byte) 0); 1210 fields.put("maximumIntegerDigits", dform.getMaximumIntegerDigits()); 1211 fields.put("minimumIntegerDigits", dform.getMinimumIntegerDigits()); 1212 fields.put("maximumFractionDigits", dform.getMaximumFractionDigits()); 1213 fields.put("minimumFractionDigits", dform.getMinimumFractionDigits()); 1214 fields.put("serialVersionOnStream", 4); 1215 stream.writeFields(); 1216 } 1217 1218 /** 1219 * Reads serialized fields following serialized forms specified by Java 1220 * specification. 1221 * 1222 * @param stream 1223 * the input stream to read serialized bytes 1224 * @throws IOException 1225 * if some I/O error occurs 1226 * @throws ClassNotFoundException 1227 * if some class of serialized objects or fields cannot be found 1228 */ 1229 @SuppressWarnings("nls") 1230 private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { 1231 // BEGIN android-changed 1232 ObjectInputStream.GetField fields = stream.readFields(); 1233 this.symbols = (DecimalFormatSymbols) fields.get("symbols", null); 1234 1235 initNative(""); 1236 dform.setPositivePrefix((String) fields.get("positivePrefix", "")); 1237 dform.setPositiveSuffix((String) fields.get("positiveSuffix", "")); 1238 dform.setNegativePrefix((String) fields.get("negativePrefix", "-")); 1239 dform.setNegativeSuffix((String) fields.get("negativeSuffix", "")); 1240 dform.setMultiplier(fields.get("multiplier", 1)); 1241 dform.setGroupingSize(fields.get("groupingSize", (byte) 3)); 1242 dform.setGroupingUsed(fields.get("groupingUsed", true)); 1243 dform.setDecimalSeparatorAlwaysShown(fields.get("decimalSeparatorAlwaysShown", false)); 1244 1245 setRoundingMode((RoundingMode) fields.get("roundingMode", RoundingMode.HALF_EVEN)); 1246 1247 final int maximumIntegerDigits = fields.get("maximumIntegerDigits", 309); 1248 final int minimumIntegerDigits = fields.get("minimumIntegerDigits", 309); 1249 final int maximumFractionDigits = fields.get("maximumFractionDigits", 340); 1250 final int minimumFractionDigits = fields.get("minimumFractionDigits", 340); 1251 // BEGIN android-changed: tell ICU what we want, then ask it what we can have, and then 1252 // set that in our Java object. This isn't RI-compatible, but then very little of our 1253 // behavior in this area is, and it's not obvious how we can second-guess ICU (or tell 1254 // it to just do exactly what we ask). We only need to do this with maximumIntegerDigits 1255 // because ICU doesn't seem to have its own ideas about the other options. 1256 dform.setMaximumIntegerDigits(maximumIntegerDigits); 1257 super.setMaximumIntegerDigits(dform.getMaximumIntegerDigits()); 1258 1259 setMinimumIntegerDigits(minimumIntegerDigits); 1260 setMinimumFractionDigits(minimumFractionDigits); 1261 setMaximumFractionDigits(maximumFractionDigits); 1262 setParseBigDecimal(fields.get("parseBigDecimal", false)); 1263 1264 if (fields.get("serialVersionOnStream", 0) < 3) { 1265 setMaximumIntegerDigits(super.getMaximumIntegerDigits()); 1266 setMinimumIntegerDigits(super.getMinimumIntegerDigits()); 1267 setMaximumFractionDigits(super.getMaximumFractionDigits()); 1268 setMinimumFractionDigits(super.getMinimumFractionDigits()); 1269 } 1270 // END android-changed 1271 } 1272 1273 /** 1274 * Returns the {@code RoundingMode} used by this {@code NumberFormat}. 1275 * @since 1.6 1276 */ 1277 public RoundingMode getRoundingMode() { 1278 return roundingMode; 1279 } 1280 1281 /** 1282 * Sets the {@code RoundingMode} used by this {@code NumberFormat}. 1283 * @since 1.6 1284 */ 1285 public void setRoundingMode(RoundingMode roundingMode) { 1286 if (roundingMode == null) { 1287 throw new NullPointerException(); 1288 } 1289 this.roundingMode = roundingMode; 1290 if (roundingMode != RoundingMode.UNNECESSARY) { // ICU4C doesn't support UNNECESSARY. 1291 double roundingIncrement = 1.0 / Math.pow(10, Math.max(0, getMaximumFractionDigits())); 1292 dform.setRoundingMode(roundingMode, roundingIncrement); 1293 } 1294 } 1295} 1296