1. /*
  2. * @(#)DecimalFormat.java 1.79 04/06/28
  3. *
  4. * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. /*
  8. * (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
  9. * (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved
  10. *
  11. * The original version of this source code and documentation is copyrighted
  12. * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These
  13. * materials are provided under terms of a License Agreement between Taligent
  14. * and Sun. This technology is protected by multiple US and International
  15. * patents. This notice and attribution to Taligent may not be removed.
  16. * Taligent is a registered trademark of Taligent, Inc.
  17. *
  18. */
  19. package java.text;
  20. import java.io.InvalidObjectException;
  21. import java.io.IOException;
  22. import java.io.ObjectInputStream;
  23. import java.math.BigDecimal;
  24. import java.math.BigInteger;
  25. import java.util.ArrayList;
  26. import java.util.Currency;
  27. import java.util.Hashtable;
  28. import java.util.Locale;
  29. import java.util.ResourceBundle;
  30. import sun.text.resources.LocaleData;
  31. /**
  32. * <code>DecimalFormat</code> is a concrete subclass of
  33. * <code>NumberFormat</code> that formats decimal numbers. It has a variety of
  34. * features designed to make it possible to parse and format numbers in any
  35. * locale, including support for Western, Arabic, and Indic digits. It also
  36. * supports different kinds of numbers, including integers (123), fixed-point
  37. * numbers (123.4), scientific notation (1.23E4), percentages (12%), and
  38. * currency amounts ($123). All of these can be localized.
  39. *
  40. * <p>To obtain a <code>NumberFormat</code> for a specific locale, including the
  41. * default locale, call one of <code>NumberFormat</code>'s factory methods, such
  42. * as <code>getInstance()</code>. In general, do not call the
  43. * <code>DecimalFormat</code> constructors directly, since the
  44. * <code>NumberFormat</code> factory methods may return subclasses other than
  45. * <code>DecimalFormat</code>. If you need to customize the format object, do
  46. * something like this:
  47. *
  48. * <blockquote><pre>
  49. * NumberFormat f = NumberFormat.getInstance(loc);
  50. * if (f instanceof DecimalFormat) {
  51. * ((DecimalFormat) f).setDecimalSeparatorAlwaysShown(true);
  52. * }
  53. * </pre></blockquote>
  54. *
  55. * <p>A <code>DecimalFormat</code> comprises a <em>pattern</em> and a set of
  56. * <em>symbols</em>. The pattern may be set directly using
  57. * <code>applyPattern()</code>, or indirectly using the API methods. The
  58. * symbols are stored in a <code>DecimalFormatSymbols</code> object. When using
  59. * the <code>NumberFormat</code> factory methods, the pattern and symbols are
  60. * read from localized <code>ResourceBundle</code>s.
  61. *
  62. * <h4>Patterns</h4>
  63. *
  64. * <code>DecimalFormat</code> patterns have the following syntax:
  65. * <blockquote><pre>
  66. * <i>Pattern:</i>
  67. * <i>PositivePattern</i>
  68. * <i>PositivePattern</i> ; <i>NegativePattern</i>
  69. * <i>PositivePattern:</i>
  70. * <i>Prefix<sub>opt</sub></i> <i>Number</i> <i>Suffix<sub>opt</sub></i>
  71. * <i>NegativePattern:</i>
  72. * <i>Prefix<sub>opt</sub></i> <i>Number</i> <i>Suffix<sub>opt</sub></i>
  73. * <i>Prefix:</i>
  74. * any Unicode characters except \uFFFE, \uFFFF, and special characters
  75. * <i>Suffix:</i>
  76. * any Unicode characters except \uFFFE, \uFFFF, and special characters
  77. * <i>Number:</i>
  78. * <i>Integer</i> <i>Exponent<sub>opt</sub></i>
  79. * <i>Integer</i> . <i>Fraction</i> <i>Exponent<sub>opt</sub></i>
  80. * <i>Integer:</i>
  81. * <i>MinimumInteger</i>
  82. * #
  83. * # <i>Integer</i>
  84. * # , <i>Integer</i>
  85. * <i>MinimumInteger:</i>
  86. * 0
  87. * 0 <i>MinimumInteger</i>
  88. * 0 , <i>MinimumInteger</i>
  89. * <i>Fraction:</i>
  90. * <i>MinimumFraction<sub>opt</sub></i> <i>OptionalFraction<sub>opt</sub></i>
  91. * <i>MinimumFraction:</i>
  92. * 0 <i>MinimumFraction<sub>opt</sub></i>
  93. * <i>OptionalFraction:</i>
  94. * # <i>OptionalFraction<sub>opt</sub></i>
  95. * <i>Exponent:</i>
  96. * E <i>MinimumExponent</i>
  97. * <i>MinimumExponent:</i>
  98. * 0 <i>MinimumExponent<sub>opt</sub></i>
  99. * </pre></blockquote>
  100. *
  101. * <p>A <code>DecimalFormat</code> pattern contains a positive and negative
  102. * subpattern, for example, <code>"#,##0.00;(#,##0.00)"</code>. Each
  103. * subpattern has a prefix, numeric part, and suffix. The negative subpattern
  104. * is optional; if absent, then the positive subpattern prefixed with the
  105. * localized minus sign (<code>'-'</code> in most locales) is used as the
  106. * negative subpattern. That is, <code>"0.00"</code> alone is equivalent to
  107. * <code>"0.00;-0.00"</code>. If there is an explicit negative subpattern, it
  108. * serves only to specify the negative prefix and suffix; the number of digits,
  109. * minimal digits, and other characteristics are all the same as the positive
  110. * pattern. That means that <code>"#,##0.0#;(#)"</code> produces precisely
  111. * the same behavior as <code>"#,##0.0#;(#,##0.0#)"</code>.
  112. *
  113. * <p>The prefixes, suffixes, and various symbols used for infinity, digits,
  114. * thousands separators, decimal separators, etc. may be set to arbitrary
  115. * values, and they will appear properly during formatting. However, care must
  116. * be taken that the symbols and strings do not conflict, or parsing will be
  117. * unreliable. For example, either the positive and negative prefixes or the
  118. * suffixes must be distinct for <code>DecimalFormat.parse()</code> to be able
  119. * to distinguish positive from negative values. (If they are identical, then
  120. * <code>DecimalFormat</code> will behave as if no negative subpattern was
  121. * specified.) Another example is that the decimal separator and thousands
  122. * separator should be distinct characters, or parsing will be impossible.
  123. *
  124. * <p>The grouping separator is commonly used for thousands, but in some
  125. * countries it separates ten-thousands. The grouping size is a constant number
  126. * of digits between the grouping characters, such as 3 for 100,000,000 or 4 for
  127. * 1,0000,0000. If you supply a pattern with multiple grouping characters, the
  128. * interval between the last one and the end of the integer is the one that is
  129. * used. So <code>"#,##,###,####"</code> == <code>"######,####"</code> ==
  130. * <code>"##,####,####"</code>.
  131. *
  132. * <h4>Special Pattern Characters</h4>
  133. *
  134. * <p>Many characters in a pattern are taken literally; they are matched during
  135. * parsing and output unchanged during formatting. Special characters, on the
  136. * other hand, stand for other characters, strings, or classes of characters.
  137. * They must be quoted, unless noted otherwise, if they are to appear in the
  138. * prefix or suffix as literals.
  139. *
  140. * <p>The characters listed here are used in non-localized patterns. Localized
  141. * patterns use the corresponding characters taken from this formatter's
  142. * <code>DecimalFormatSymbols</code> object instead, and these characters lose
  143. * their special status. Two exceptions are the currency sign and quote, which
  144. * are not localized.
  145. *
  146. * <blockquote>
  147. * <table border=0 cellspacing=3 cellpadding=0 summary="Chart showing symbol,
  148. * location, localized, and meaning.">
  149. * <tr bgcolor="#ccccff">
  150. * <th align=left>Symbol
  151. * <th align=left>Location
  152. * <th align=left>Localized?
  153. * <th align=left>Meaning
  154. * <tr valign=top>
  155. * <td><code>0</code>
  156. * <td>Number
  157. * <td>Yes
  158. * <td>Digit
  159. * <tr valign=top bgcolor="#eeeeff">
  160. * <td><code>#</code>
  161. * <td>Number
  162. * <td>Yes
  163. * <td>Digit, zero shows as absent
  164. * <tr valign=top>
  165. * <td><code>.</code>
  166. * <td>Number
  167. * <td>Yes
  168. * <td>Decimal separator or monetary decimal separator
  169. * <tr valign=top bgcolor="#eeeeff">
  170. * <td><code>-</code>
  171. * <td>Number
  172. * <td>Yes
  173. * <td>Minus sign
  174. * <tr valign=top>
  175. * <td><code>,</code>
  176. * <td>Number
  177. * <td>Yes
  178. * <td>Grouping separator
  179. * <tr valign=top bgcolor="#eeeeff">
  180. * <td><code>E</code>
  181. * <td>Number
  182. * <td>Yes
  183. * <td>Separates mantissa and exponent in scientific notation.
  184. * <em>Need not be quoted in prefix or suffix.</em>
  185. * <tr valign=top>
  186. * <td><code></code>
  187. * <td>Subpattern boundary
  188. * <td>Yes
  189. * <td>Separates positive and negative subpatterns
  190. * <tr valign=top bgcolor="#eeeeff">
  191. * <td><code>%</code>
  192. * <td>Prefix or suffix
  193. * <td>Yes
  194. * <td>Multiply by 100 and show as percentage
  195. * <tr valign=top>
  196. * <td><code>\u2030</code>
  197. * <td>Prefix or suffix
  198. * <td>Yes
  199. * <td>Multiply by 1000 and show as per mille value
  200. * <tr valign=top bgcolor="#eeeeff">
  201. * <td><code>¤</code> (<code>\u00A4</code>)
  202. * <td>Prefix or suffix
  203. * <td>No
  204. * <td>Currency sign, replaced by currency symbol. If
  205. * doubled, replaced by international currency symbol.
  206. * If present in a pattern, the monetary decimal separator
  207. * is used instead of the decimal separator.
  208. * <tr valign=top>
  209. * <td><code>'</code>
  210. * <td>Prefix or suffix
  211. * <td>No
  212. * <td>Used to quote special characters in a prefix or suffix,
  213. * for example, <code>"'#'#"</code> formats 123 to
  214. * <code>"#123"</code>. To create a single quote
  215. * itself, use two in a row: <code>"# o''clock"</code>.
  216. * </table>
  217. * </blockquote>
  218. *
  219. * <h4>Scientific Notation</h4>
  220. *
  221. * <p>Numbers in scientific notation are expressed as the product of a mantissa
  222. * and a power of ten, for example, 1234 can be expressed as 1.234 x 10^3. The
  223. * mantissa is often in the range 1.0 <= x < 10.0, but it need not be.
  224. * <code>DecimalFormat</code> can be instructed to format and parse scientific
  225. * notation <em>only via a pattern</em> there is currently no factory method
  226. * that creates a scientific notation format. In a pattern, the exponent
  227. * character immediately followed by one or more digit characters indicates
  228. * scientific notation. Example: <code>"0.###E0"</code> formats the number
  229. * 1234 as <code>"1.234E3"</code>.
  230. *
  231. * <ul>
  232. * <li>The number of digit characters after the exponent character gives the
  233. * minimum exponent digit count. There is no maximum. Negative exponents are
  234. * formatted using the localized minus sign, <em>not</em> the prefix and suffix
  235. * from the pattern. This allows patterns such as <code>"0.###E0 m/s"</code>.
  236. *
  237. * <li>The minimum and maximum number of integer digits are interpreted
  238. * together:
  239. *
  240. * <ul>
  241. * <li>If the maximum number of integer digits is greater than their minimum number
  242. * and greater than 1, it forces the exponent to be a multiple of the maximum
  243. * number of integer digits, and the minimum number of integer digits to be
  244. * interpreted as 1. The most common use of this is to generate
  245. * <em>engineering notation</em>, in which the exponent is a multiple of three,
  246. * e.g., <code>"##0.#####E0"</code>. Using this pattern, the number 12345
  247. * formats to <code>"12.345E3"</code>, and 123456 formats to
  248. * <code>"123.456E3"</code>.
  249. *
  250. * <li>Otherwise, the minimum number of integer digits is achieved by adjusting the
  251. * exponent. Example: 0.00123 formatted with <code>"00.###E0"</code> yields
  252. * <code>"12.3E-4"</code>.
  253. * </ul>
  254. *
  255. * <li>The number of significant digits in the mantissa is the sum of the
  256. * <em>minimum integer</em> and <em>maximum fraction</em> digits, and is
  257. * unaffected by the maximum integer digits. For example, 12345 formatted with
  258. * <code>"##0.##E0"</code> is <code>"12.3E3"</code>. To show all digits, set
  259. * the significant digits count to zero. The number of significant digits
  260. * does not affect parsing.
  261. *
  262. * <li>Exponential patterns may not contain grouping separators.
  263. * </ul>
  264. *
  265. * <h4>Rounding</h4>
  266. *
  267. * <code>DecimalFormat</code> uses half-even rounding (see
  268. * {@link java.math.BigDecimal#ROUND_HALF_EVEN ROUND_HALF_EVEN}) for
  269. * formatting.
  270. *
  271. * <h4>Digits</h4>
  272. *
  273. * For formatting, <code>DecimalFormat</code> uses the ten consecutive
  274. * characters starting with the localized zero digit defined in the
  275. * <code>DecimalFormatSymbols</code> object as digits. For parsing, these
  276. * digits as well as all Unicode decimal digits, as defined by
  277. * {@link Character#digit Character.digit}, are recognized.
  278. *
  279. * <h4>Special Values</h4>
  280. *
  281. * <p><code>NaN</code> is formatted as a single character, typically
  282. * <code>\uFFFD</code>. This character is determined by the
  283. * <code>DecimalFormatSymbols</code> object. This is the only value for which
  284. * the prefixes and suffixes are not used.
  285. *
  286. * <p>Infinity is formatted as a single character, typically
  287. * <code>\u221E</code>, with the positive or negative prefixes and suffixes
  288. * applied. The infinity character is determined by the
  289. * <code>DecimalFormatSymbols</code> object.
  290. *
  291. * <p>Negative zero (<code>"-0"</code>) parses to
  292. * <ul>
  293. * <li><code>BigDecimal(0)</code> if <code>isParseBigDecimal()</code> is
  294. * true,
  295. * <li><code>Long(0)</code> if <code>isParseBigDecimal()</code> is false
  296. * and <code>isParseIntegerOnly()</code> is true,
  297. * <li><code>Double(-0.0)</code> if both <code>isParseBigDecimal()</code>
  298. * and <code>isParseIntegerOnly()</code> are false.
  299. * </ul>
  300. *
  301. * <h4><a name="synchronization">Synchronization</a></h4>
  302. *
  303. * <p>
  304. * Decimal formats are generally not synchronized.
  305. * It is recommended to create separate format instances for each thread.
  306. * If multiple threads access a format concurrently, it must be synchronized
  307. * externally.
  308. *
  309. * <h4>Example</h4>
  310. *
  311. * <blockquote><pre>
  312. * <strong>// Print out a number using the localized number, integer, currency,
  313. * // and percent format for each locale</strong>
  314. * Locale[] locales = NumberFormat.getAvailableLocales();
  315. * double myNumber = -1234.56;
  316. * NumberFormat form;
  317. * for (int j=0; j<4; ++j) {
  318. * System.out.println("FORMAT");
  319. * for (int i = 0; i < locales.length; ++i) {
  320. * if (locales[i].getCountry().length() == 0) {
  321. * continue; // Skip language-only locales
  322. * }
  323. * System.out.print(locales[i].getDisplayName());
  324. * switch (j) {
  325. * case 0:
  326. * form = NumberFormat.getInstance(locales[i]); break;
  327. * case 1:
  328. * form = NumberFormat.getIntegerInstance(locales[i]); break;
  329. * case 2:
  330. * form = NumberFormat.getCurrencyInstance(locales[i]); break;
  331. * default:
  332. * form = NumberFormat.getPercentInstance(locales[i]); break;
  333. * }
  334. * if (form instanceof DecimalFormat) {
  335. * System.out.print(": " + ((DecimalFormat) form).toPattern());
  336. * }
  337. * System.out.print(" -> " + form.format(myNumber));
  338. * try {
  339. * System.out.println(" -> " + form.parse(form.format(myNumber)));
  340. * } catch (ParseException e) {}
  341. * }
  342. * }
  343. * </pre></blockquote>
  344. *
  345. * @see <a href="http://java.sun.com/docs/books/tutorial/i18n/format/decimalFormat.html">Java Tutorial</a>
  346. * @see NumberFormat
  347. * @see DecimalFormatSymbols
  348. * @see ParsePosition
  349. * @version 1.79 06/28/04
  350. * @author Mark Davis
  351. * @author Alan Liu
  352. */
  353. public class DecimalFormat extends NumberFormat {
  354. /**
  355. * Creates a DecimalFormat using the default pattern and symbols
  356. * for the default locale. This is a convenient way to obtain a
  357. * DecimalFormat when internationalization is not the main concern.
  358. * <p>
  359. * To obtain standard formats for a given locale, use the factory methods
  360. * on NumberFormat such as getNumberInstance. These factories will
  361. * return the most appropriate sub-class of NumberFormat for a given
  362. * locale.
  363. *
  364. * @see java.text.NumberFormat#getInstance
  365. * @see java.text.NumberFormat#getNumberInstance
  366. * @see java.text.NumberFormat#getCurrencyInstance
  367. * @see java.text.NumberFormat#getPercentInstance
  368. */
  369. public DecimalFormat() {
  370. Locale def = Locale.getDefault();
  371. // try to get the pattern from the cache
  372. String pattern = (String) cachedLocaleData.get(def);
  373. if (pattern == null) { /* cache miss */
  374. // Get the pattern for the default locale.
  375. ResourceBundle rb = LocaleData.getLocaleElements(def);
  376. String[] all = rb.getStringArray("NumberPatterns");
  377. pattern = all[0];
  378. /* update cache */
  379. cachedLocaleData.put(def, pattern);
  380. }
  381. // Always applyPattern after the symbols are set
  382. this.symbols = new DecimalFormatSymbols(def);
  383. applyPattern(pattern, false);
  384. }
  385. /**
  386. * Creates a DecimalFormat using the given pattern and the symbols
  387. * for the default locale. This is a convenient way to obtain a
  388. * DecimalFormat when internationalization is not the main concern.
  389. * <p>
  390. * To obtain standard formats for a given locale, use the factory methods
  391. * on NumberFormat such as getNumberInstance. These factories will
  392. * return the most appropriate sub-class of NumberFormat for a given
  393. * locale.
  394. *
  395. * @param pattern A non-localized pattern string.
  396. * @exception NullPointerException if <code>pattern</code> is null
  397. * @exception IllegalArgumentException if the given pattern is invalid.
  398. * @see java.text.NumberFormat#getInstance
  399. * @see java.text.NumberFormat#getNumberInstance
  400. * @see java.text.NumberFormat#getCurrencyInstance
  401. * @see java.text.NumberFormat#getPercentInstance
  402. */
  403. public DecimalFormat(String pattern) {
  404. // Always applyPattern after the symbols are set
  405. this.symbols = new DecimalFormatSymbols(Locale.getDefault());
  406. applyPattern(pattern, false);
  407. }
  408. /**
  409. * Creates a DecimalFormat using the given pattern and symbols.
  410. * Use this constructor when you need to completely customize the
  411. * behavior of the format.
  412. * <p>
  413. * To obtain standard formats for a given
  414. * locale, use the factory methods on NumberFormat such as
  415. * getInstance or getCurrencyInstance. If you need only minor adjustments
  416. * to a standard format, you can modify the format returned by
  417. * a NumberFormat factory method.
  418. *
  419. * @param pattern a non-localized pattern string
  420. * @param symbols the set of symbols to be used
  421. * @exception NullPointerException if any of the given arguments is null
  422. * @exception IllegalArgumentException if the given pattern is invalid
  423. * @see java.text.NumberFormat#getInstance
  424. * @see java.text.NumberFormat#getNumberInstance
  425. * @see java.text.NumberFormat#getCurrencyInstance
  426. * @see java.text.NumberFormat#getPercentInstance
  427. * @see java.text.DecimalFormatSymbols
  428. */
  429. public DecimalFormat (String pattern, DecimalFormatSymbols symbols) {
  430. // Always applyPattern after the symbols are set
  431. this.symbols = (DecimalFormatSymbols)symbols.clone();
  432. applyPattern(pattern, false);
  433. }
  434. // Overrides
  435. /**
  436. * Formats a number and appends the resulting text to the given string
  437. * buffer.
  438. * The number can be of any subclass of {@link java.lang.Number}.
  439. * <p>
  440. * This implementation uses the maximum precision permitted.
  441. * @param number the number to format
  442. * @param toAppendTo the <code>StringBuffer</code> to which the formatted
  443. * text is to be appended
  444. * @param pos On input: an alignment field, if desired.
  445. * On output: the offsets of the alignment field.
  446. * @return the value passed in as <code>toAppendTo</code>
  447. * @exception IllegalArgumentException if <code>number</code> is
  448. * null or not an instance of <code>Number</code>.
  449. * @exception NullPointerException if <code>toAppendTo</code> or
  450. * <code>pos</code> is null
  451. * @see java.text.FieldPosition
  452. */
  453. public final StringBuffer format(Object number,
  454. StringBuffer toAppendTo,
  455. FieldPosition pos) {
  456. if (number instanceof Long || number instanceof Integer ||
  457. number instanceof Short || number instanceof Byte ||
  458. (number instanceof BigInteger &&
  459. ((BigInteger)number).bitLength () < 64)) {
  460. return format(((Number)number).longValue(), toAppendTo, pos);
  461. } else if (number instanceof BigDecimal) {
  462. return format((BigDecimal)number, toAppendTo, pos);
  463. } else if (number instanceof BigInteger) {
  464. return format((BigInteger)number, toAppendTo, pos);
  465. } else if (number instanceof Number) {
  466. return format(((Number)number).doubleValue(), toAppendTo, pos);
  467. } else {
  468. throw new IllegalArgumentException("Cannot format given Object as a Number");
  469. }
  470. }
  471. /**
  472. * Formats a double to produce a string.
  473. * @param number The double to format
  474. * @param result where the text is to be appended
  475. * @param fieldPosition On input: an alignment field, if desired.
  476. * On output: the offsets of the alignment field.
  477. * @return The formatted number string
  478. * @see java.text.FieldPosition
  479. */
  480. public StringBuffer format(double number, StringBuffer result,
  481. FieldPosition fieldPosition) {
  482. fieldPosition.setBeginIndex(0);
  483. fieldPosition.setEndIndex(0);
  484. return format(number, result, fieldPosition.getFieldDelegate());
  485. }
  486. /**
  487. * Formats a double to produce a string.
  488. * @param number The double to format
  489. * @param result where the text is to be appended
  490. * @param delegate notified of locations of sub fields
  491. * @return The formatted number string
  492. */
  493. private StringBuffer format(double number, StringBuffer result,
  494. FieldDelegate delegate) {
  495. if (Double.isNaN(number) ||
  496. (Double.isInfinite(number) && multiplier == 0)) {
  497. int iFieldStart = result.length();
  498. result.append(symbols.getNaN());
  499. delegate.formatted(INTEGER_FIELD, Field.INTEGER, Field.INTEGER,
  500. iFieldStart, result.length(), result);
  501. return result;
  502. }
  503. /* Detecting whether a double is negative is easy with the exception of
  504. * the value -0.0. This is a double which has a zero mantissa (and
  505. * exponent), but a negative sign bit. It is semantically distinct from
  506. * a zero with a positive sign bit, and this distinction is important
  507. * to certain kinds of computations. However, it's a little tricky to
  508. * detect, since (-0.0 == 0.0) and !(-0.0 < 0.0). How then, you may
  509. * ask, does it behave distinctly from +0.0? Well, 1/(-0.0) ==
  510. * -Infinity. Proper detection of -0.0 is needed to deal with the
  511. * issues raised by bugs 4106658, 4106667, and 4147706. Liu 7/6/98.
  512. */
  513. boolean isNegative = ((number < 0.0) || (number == 0.0 && 1/number < 0.0)) ^ (multiplier < 0);
  514. if (multiplier != 1) {
  515. number *= multiplier;
  516. }
  517. if (Double.isInfinite(number)) {
  518. if (isNegative) {
  519. append(result, negativePrefix, delegate,
  520. getNegativePrefixFieldPositions(), Field.SIGN);
  521. } else {
  522. append(result, positivePrefix, delegate,
  523. getPositivePrefixFieldPositions(), Field.SIGN);
  524. }
  525. int iFieldStart = result.length();
  526. result.append(symbols.getInfinity());
  527. delegate.formatted(INTEGER_FIELD, Field.INTEGER, Field.INTEGER,
  528. iFieldStart, result.length(), result);
  529. if (isNegative) {
  530. append(result, negativeSuffix, delegate,
  531. getNegativeSuffixFieldPositions(), Field.SIGN);
  532. } else {
  533. append(result, positiveSuffix, delegate,
  534. getPositiveSuffixFieldPositions(), Field.SIGN);
  535. }
  536. return result;
  537. }
  538. if (isNegative) {
  539. number = -number;
  540. }
  541. // at this point we are guaranteed a nonnegative finite number.
  542. assert(number >= 0 && !Double.isInfinite(number));
  543. synchronized(digitList) {
  544. int maxIntDigits = super.getMaximumIntegerDigits();
  545. int minIntDigits = super.getMinimumIntegerDigits();
  546. int maxFraDigits = super.getMaximumFractionDigits();
  547. int minFraDigits = super.getMinimumFractionDigits();
  548. digitList.set(number, useExponentialNotation ?
  549. maxIntDigits + maxFraDigits : maxFraDigits,
  550. !useExponentialNotation);
  551. return subformat(result, delegate, isNegative, false,
  552. maxIntDigits, minIntDigits, maxFraDigits, minFraDigits);
  553. }
  554. }
  555. /**
  556. * Format a long to produce a string.
  557. * @param number The long to format
  558. * @param result where the text is to be appended
  559. * @param fieldPosition On input: an alignment field, if desired.
  560. * On output: the offsets of the alignment field.
  561. * @return The formatted number string
  562. * @see java.text.FieldPosition
  563. */
  564. public StringBuffer format(long number, StringBuffer result,
  565. FieldPosition fieldPosition) {
  566. fieldPosition.setBeginIndex(0);
  567. fieldPosition.setEndIndex(0);
  568. return format(number, result, fieldPosition.getFieldDelegate());
  569. }
  570. /**
  571. * Format a long to produce a string.
  572. * @param number The long to format
  573. * @param result where the text is to be appended
  574. * @param delegate notified of locations of sub fields
  575. * @return The formatted number string
  576. * @see java.text.FieldPosition
  577. */
  578. private StringBuffer format(long number, StringBuffer result,
  579. FieldDelegate delegate) {
  580. boolean isNegative = (number < 0);
  581. if (isNegative) {
  582. number = -number;
  583. }
  584. // In general, long values always represent real finite numbers, so
  585. // we don't have to check for +/- Infinity or NaN. However, there
  586. // is one case we have to be careful of: The multiplier can push
  587. // a number near MIN_VALUE or MAX_VALUE outside the legal range. We
  588. // check for this before multiplying, and if it happens we use
  589. // BigInteger instead.
  590. boolean useBigInteger = false;
  591. if (number < 0) { // This can only happen if number == Long.MIN_VALUE.
  592. if (multiplier != 0) {
  593. useBigInteger = true;
  594. }
  595. } else if (multiplier != 1 && multiplier != 0) {
  596. long cutoff = Long.MAX_VALUE / multiplier;
  597. if (cutoff < 0) {
  598. cutoff = -cutoff;
  599. }
  600. useBigInteger = (number > cutoff);
  601. }
  602. if (useBigInteger) {
  603. if (isNegative) {
  604. number = -number;
  605. }
  606. BigInteger bigIntegerValue = BigInteger.valueOf(number);
  607. return format(bigIntegerValue, result, delegate, true);
  608. }
  609. number *= multiplier;
  610. if (number == 0) {
  611. isNegative = false;
  612. } else {
  613. if (multiplier < 0) {
  614. number = -number;
  615. isNegative = !isNegative;
  616. }
  617. }
  618. synchronized(digitList) {
  619. int maxIntDigits = super.getMaximumIntegerDigits();
  620. int minIntDigits = super.getMinimumIntegerDigits();
  621. int maxFraDigits = super.getMaximumFractionDigits();
  622. int minFraDigits = super.getMinimumFractionDigits();
  623. digitList.set(number,
  624. useExponentialNotation ? maxIntDigits + maxFraDigits : 0);
  625. return subformat(result, delegate, isNegative, true,
  626. maxIntDigits, minIntDigits, maxFraDigits, minFraDigits);
  627. }
  628. }
  629. /**
  630. * Formats a BigDecimal to produce a string.
  631. * @param number The BigDecimal to format
  632. * @param result where the text is to be appended
  633. * @param fieldPosition On input: an alignment field, if desired.
  634. * On output: the offsets of the alignment field.
  635. * @return The formatted number string
  636. * @see java.text.FieldPosition
  637. */
  638. private StringBuffer format(BigDecimal number, StringBuffer result,
  639. FieldPosition fieldPosition) {
  640. fieldPosition.setBeginIndex(0);
  641. fieldPosition.setEndIndex(0);
  642. return format(number, result, fieldPosition.getFieldDelegate());
  643. }
  644. /**
  645. * Formats a BigDecimal to produce a string.
  646. * @param number The BigDecimal to format
  647. * @param result where the text is to be appended
  648. * @param delegate notified of locations of sub fields
  649. * @return The formatted number string
  650. */
  651. private StringBuffer format(BigDecimal number, StringBuffer result,
  652. FieldDelegate delegate) {
  653. if (multiplier != 1) {
  654. number = number.multiply(getBigDecimalMultiplier());
  655. }
  656. boolean isNegative = number.signum() == -1;
  657. if (isNegative) {
  658. number = number.negate();
  659. }
  660. synchronized(digitList) {
  661. int maxIntDigits = getMaximumIntegerDigits();
  662. int minIntDigits = getMinimumIntegerDigits();
  663. int maxFraDigits = getMaximumFractionDigits();
  664. int minFraDigits = getMinimumFractionDigits();
  665. int maximumDigits = maxIntDigits + maxFraDigits;
  666. digitList.set(number, useExponentialNotation ?
  667. ((maximumDigits < 0) ? Integer.MAX_VALUE : maximumDigits) :
  668. maxFraDigits, !useExponentialNotation);
  669. return subformat(result, delegate, isNegative, false,
  670. maxIntDigits, minIntDigits, maxFraDigits, minFraDigits);
  671. }
  672. }
  673. /**
  674. * Format a BigInteger to produce a string.
  675. * @param number The BigInteger to format
  676. * @param result where the text is to be appended
  677. * @param fieldPosition On input: an alignment field, if desired.
  678. * On output: the offsets of the alignment field.
  679. * @return The formatted number string
  680. * @see java.text.FieldPosition
  681. */
  682. private StringBuffer format(BigInteger number, StringBuffer result,
  683. FieldPosition fieldPosition) {
  684. fieldPosition.setBeginIndex(0);
  685. fieldPosition.setEndIndex(0);
  686. return format(number, result, fieldPosition.getFieldDelegate(), false);
  687. }
  688. /**
  689. * Format a BigInteger to produce a string.
  690. * @param number The BigInteger to format
  691. * @param result where the text is to be appended
  692. * @param delegate notified of locations of sub fields
  693. * @return The formatted number string
  694. * @see java.text.FieldPosition
  695. */
  696. private StringBuffer format(BigInteger number, StringBuffer result,
  697. FieldDelegate delegate, boolean formatLong) {
  698. if (multiplier != 1) {
  699. number = number.multiply(getBigIntegerMultiplier());
  700. }
  701. boolean isNegative = number.signum() == -1;
  702. if (isNegative) {
  703. number = number.negate();
  704. }
  705. synchronized(digitList) {
  706. int maxIntDigits, minIntDigits, maxFraDigits, minFraDigits, maximumDigits;
  707. if (formatLong) {
  708. maxIntDigits = super.getMaximumIntegerDigits();
  709. minIntDigits = super.getMinimumIntegerDigits();
  710. maxFraDigits = super.getMaximumFractionDigits();
  711. minFraDigits = super.getMinimumFractionDigits();
  712. maximumDigits = maxIntDigits + maxFraDigits;
  713. } else {
  714. maxIntDigits = getMaximumIntegerDigits();
  715. minIntDigits = getMinimumIntegerDigits();
  716. maxFraDigits = getMaximumFractionDigits();
  717. minFraDigits = getMinimumFractionDigits();
  718. maximumDigits = maxIntDigits + maxFraDigits;
  719. if (maximumDigits < 0) {
  720. maximumDigits = Integer.MAX_VALUE;
  721. }
  722. }
  723. digitList.set(number, useExponentialNotation ? maximumDigits : 0);
  724. return subformat(result, delegate, isNegative, true,
  725. maxIntDigits, minIntDigits, maxFraDigits, minFraDigits);
  726. }
  727. }
  728. /**
  729. * Formats an Object producing an <code>AttributedCharacterIterator</code>.
  730. * You can use the returned <code>AttributedCharacterIterator</code>
  731. * to build the resulting String, as well as to determine information
  732. * about the resulting String.
  733. * <p>
  734. * Each attribute key of the AttributedCharacterIterator will be of type
  735. * <code>NumberFormat.Field</code>, with the attribute value being the
  736. * same as the attribute key.
  737. *
  738. * @exception NullPointerException if obj is null.
  739. * @exception IllegalArgumentException when the Format cannot format the
  740. * given object.
  741. * @param obj The object to format
  742. * @return AttributedCharacterIterator describing the formatted value.
  743. * @since 1.4
  744. */
  745. public AttributedCharacterIterator formatToCharacterIterator(Object obj) {
  746. CharacterIteratorFieldDelegate delegate =
  747. new CharacterIteratorFieldDelegate();
  748. StringBuffer sb = new StringBuffer();
  749. if (obj instanceof Double || obj instanceof Float) {
  750. format(((Number)obj).doubleValue(), sb, delegate);
  751. } else if (obj instanceof Long || obj instanceof Integer ||
  752. obj instanceof Short || obj instanceof Byte) {
  753. format(((Number)obj).longValue(), sb, delegate);
  754. } else if (obj instanceof BigDecimal) {
  755. format((BigDecimal)obj, sb, delegate);
  756. } else if (obj instanceof BigInteger) {
  757. format((BigInteger)obj, sb, delegate, false);
  758. } else if (obj == null) {
  759. throw new NullPointerException(
  760. "formatToCharacterIterator must be passed non-null object");
  761. } else {
  762. throw new IllegalArgumentException(
  763. "Cannot format given Object as a Number");
  764. }
  765. return delegate.getIterator(sb.toString());
  766. }
  767. /**
  768. * Complete the formatting of a finite number. On entry, the digitList must
  769. * be filled in with the correct digits.
  770. */
  771. private StringBuffer subformat(StringBuffer result, FieldDelegate delegate,
  772. boolean isNegative, boolean isInteger,
  773. int maxIntDigits, int minIntDigits,
  774. int maxFraDigits, int minFraDigits) {
  775. // NOTE: This isn't required anymore because DigitList takes care of this.
  776. //
  777. // // The negative of the exponent represents the number of leading
  778. // // zeros between the decimal and the first non-zero digit, for
  779. // // a value < 0.1 (e.g., for 0.00123, -fExponent == 2). If this
  780. // // is more than the maximum fraction digits, then we have an underflow
  781. // // for the printed representation. We recognize this here and set
  782. // // the DigitList representation to zero in this situation.
  783. //
  784. // if (-digitList.decimalAt >= getMaximumFractionDigits())
  785. // {
  786. // digitList.count = 0;
  787. // }
  788. char zero = symbols.getZeroDigit();
  789. int zeroDelta = zero - '0'; // '0' is the DigitList representation of zero
  790. char grouping = symbols.getGroupingSeparator();
  791. char decimal = isCurrencyFormat ?
  792. symbols.getMonetaryDecimalSeparator() :
  793. symbols.getDecimalSeparator();
  794. /* Per bug 4147706, DecimalFormat must respect the sign of numbers which
  795. * format as zero. This allows sensible computations and preserves
  796. * relations such as signum(1/x) = signum(x), where x is +Infinity or
  797. * -Infinity. Prior to this fix, we always formatted zero values as if
  798. * they were positive. Liu 7/6/98.
  799. */
  800. if (digitList.isZero()) {
  801. digitList.decimalAt = 0; // Normalize
  802. }
  803. if (isNegative) {
  804. append(result, negativePrefix, delegate,
  805. getNegativePrefixFieldPositions(), Field.SIGN);
  806. } else {
  807. append(result, positivePrefix, delegate,
  808. getPositivePrefixFieldPositions(), Field.SIGN);
  809. }
  810. if (useExponentialNotation) {
  811. int iFieldStart = result.length();
  812. int iFieldEnd = -1;
  813. int fFieldStart = -1;
  814. // Minimum integer digits are handled in exponential format by
  815. // adjusting the exponent. For example, 0.01234 with 3 minimum
  816. // integer digits is "123.4E-4".
  817. // Maximum integer digits are interpreted as indicating the
  818. // repeating range. This is useful for engineering notation, in
  819. // which the exponent is restricted to a multiple of 3. For
  820. // example, 0.01234 with 3 maximum integer digits is "12.34e-3".
  821. // If maximum integer digits are > 1 and are larger than
  822. // minimum integer digits, then minimum integer digits are
  823. // ignored.
  824. int exponent = digitList.decimalAt;
  825. int repeat = maxIntDigits;
  826. int minimumIntegerDigits = minIntDigits;
  827. if (repeat > 1 && repeat > minIntDigits) {
  828. // A repeating range is defined; adjust to it as follows.
  829. // If repeat == 3, we have 6,5,4=>3; 3,2,1=>0; 0,-1,-2=>-3;
  830. // -3,-4,-5=>-6, etc. This takes into account that the
  831. // exponent we have here is off by one from what we expect;
  832. // it is for the format 0.MMMMMx10^n.
  833. if (exponent >= 1) {
  834. exponent = ((exponent - 1) / repeat) * repeat;
  835. } else {
  836. // integer division rounds towards 0
  837. exponent = ((exponent - repeat) / repeat) * repeat;
  838. }
  839. minimumIntegerDigits = 1;
  840. } else {
  841. // No repeating range is defined; use minimum integer digits.
  842. exponent -= minimumIntegerDigits;
  843. }
  844. // We now output a minimum number of digits, and more if there
  845. // are more digits, up to the maximum number of digits. We
  846. // place the decimal point after the "integer" digits, which
  847. // are the first (decimalAt - exponent) digits.
  848. int minimumDigits = minIntDigits + minFraDigits;
  849. if (minimumDigits < 0) { // overflow?
  850. minimumDigits = Integer.MAX_VALUE;
  851. }
  852. // The number of integer digits is handled specially if the number
  853. // is zero, since then there may be no digits.
  854. int integerDigits = digitList.isZero() ? minimumIntegerDigits :
  855. digitList.decimalAt - exponent;
  856. if (minimumDigits < integerDigits) {
  857. minimumDigits = integerDigits;
  858. }
  859. int totalDigits = digitList.count;
  860. if (minimumDigits > totalDigits) {
  861. totalDigits = minimumDigits;
  862. }
  863. boolean addedDecimalSeparator = false;
  864. for (int i=0; i<totalDigits; ++i) {
  865. if (i == integerDigits) {
  866. // Record field information for caller.
  867. iFieldEnd = result.length();
  868. result.append(decimal);
  869. addedDecimalSeparator = true;
  870. // Record field information for caller.
  871. fFieldStart = result.length();
  872. }
  873. result.append((i < digitList.count) ?
  874. (char)(digitList.digits[i] + zeroDelta) :
  875. zero);
  876. }
  877. if (decimalSeparatorAlwaysShown && totalDigits == integerDigits) {
  878. // Record field information for caller.
  879. iFieldEnd = result.length();
  880. result.append(decimal);
  881. addedDecimalSeparator = true;
  882. // Record field information for caller.
  883. fFieldStart = result.length();
  884. }
  885. // Record field information
  886. if (iFieldEnd == -1) {
  887. iFieldEnd = result.length();
  888. }
  889. delegate.formatted(INTEGER_FIELD, Field.INTEGER, Field.INTEGER,
  890. iFieldStart, iFieldEnd, result);
  891. if (addedDecimalSeparator) {
  892. delegate.formatted(Field.DECIMAL_SEPARATOR,
  893. Field.DECIMAL_SEPARATOR,
  894. iFieldEnd, fFieldStart, result);
  895. }
  896. if (fFieldStart == -1) {
  897. fFieldStart = result.length();
  898. }
  899. delegate.formatted(FRACTION_FIELD, Field.FRACTION, Field.FRACTION,
  900. fFieldStart, result.length(), result);
  901. // The exponent is output using the pattern-specified minimum
  902. // exponent digits. There is no maximum limit to the exponent
  903. // digits, since truncating the exponent would result in an
  904. // unacceptable inaccuracy.
  905. int fieldStart = result.length();
  906. result.append(symbols.getExponentialSymbol());
  907. delegate.formatted(Field.EXPONENT_SYMBOL, Field.EXPONENT_SYMBOL,
  908. fieldStart, result.length(), result);
  909. // For zero values, we force the exponent to zero. We
  910. // must do this here, and not earlier, because the value
  911. // is used to determine integer digit count above.
  912. if (digitList.isZero()) {
  913. exponent = 0;
  914. }
  915. boolean negativeExponent = exponent < 0;
  916. if (negativeExponent) {
  917. exponent = -exponent;
  918. fieldStart = result.length();
  919. result.append(symbols.getMinusSign());
  920. delegate.formatted(Field.EXPONENT_SIGN, Field.EXPONENT_SIGN,
  921. fieldStart, result.length(), result);
  922. }
  923. digitList.set(exponent);
  924. int eFieldStart = result.length();
  925. for (int i=digitList.decimalAt; i<minExponentDigits; ++i) {
  926. result.append(zero);
  927. }
  928. for (int i=0; i<digitList.decimalAt; ++i) {
  929. result.append((i < digitList.count) ?
  930. (char)(digitList.digits[i] + zeroDelta) : zero);
  931. }
  932. delegate.formatted(Field.EXPONENT, Field.EXPONENT, eFieldStart,
  933. result.length(), result);
  934. } else {
  935. int iFieldStart = result.length();
  936. // Output the integer portion. Here 'count' is the total
  937. // number of integer digits we will display, including both
  938. // leading zeros required to satisfy getMinimumIntegerDigits,
  939. // and actual digits present in the number.
  940. int count = minIntDigits;
  941. int digitIndex = 0; // Index into digitList.fDigits[]
  942. if (digitList.decimalAt > 0 && count < digitList.decimalAt) {
  943. count = digitList.decimalAt;
  944. }
  945. // Handle the case where getMaximumIntegerDigits() is smaller
  946. // than the real number of integer digits. If this is so, we
  947. // output the least significant max integer digits. For example,
  948. // the value 1997 printed with 2 max integer digits is just "97".
  949. if (count > maxIntDigits) {
  950. count = maxIntDigits;
  951. digitIndex = digitList.decimalAt - count;
  952. }
  953. int sizeBeforeIntegerPart = result.length();
  954. for (int i=count-1; i>=0; --i) {
  955. if (i < digitList.decimalAt && digitIndex < digitList.count) {
  956. // Output a real digit
  957. result.append((char)(digitList.digits[digitIndex++] + zeroDelta));
  958. } else {
  959. // Output a leading zero
  960. result.append(zero);
  961. }
  962. // Output grouping separator if necessary. Don't output a
  963. // grouping separator if i==0 though; that's at the end of
  964. // the integer part.
  965. if (isGroupingUsed() && i>0 && (groupingSize != 0) &&
  966. (i % groupingSize == 0)) {
  967. int gStart = result.length();
  968. result.append(grouping);
  969. delegate.formatted(Field.GROUPING_SEPARATOR,
  970. Field.GROUPING_SEPARATOR, gStart,
  971. result.length(), result);
  972. }
  973. }
  974. // Determine whether or not there are any printable fractional
  975. // digits. If we've used up the digits we know there aren't.
  976. boolean fractionPresent = (minFraDigits > 0) ||
  977. (!isInteger && digitIndex < digitList.count);
  978. // If there is no fraction present, and we haven't printed any
  979. // integer digits, then print a zero. Otherwise we won't print
  980. // _any_ digits, and we won't be able to parse this string.
  981. if (!fractionPresent && result.length() == sizeBeforeIntegerPart) {
  982. result.append(zero);
  983. }
  984. delegate.formatted(INTEGER_FIELD, Field.INTEGER, Field.INTEGER,
  985. iFieldStart, result.length(), result);
  986. // Output the decimal separator if we always do so.
  987. int sStart = result.length();
  988. if (decimalSeparatorAlwaysShown || fractionPresent) {
  989. result.append(decimal);
  990. }
  991. if (sStart != result.length()) {
  992. delegate.formatted(Field.DECIMAL_SEPARATOR,
  993. Field.DECIMAL_SEPARATOR,
  994. sStart, result.length(), result);
  995. }
  996. int fFieldStart = result.length();
  997. for (int i=0; i < maxFraDigits; ++i) {
  998. // Here is where we escape from the loop. We escape if we've
  999. // output the maximum fraction digits (specified in the for
  1000. // expression above).
  1001. // We also stop when we've output the minimum digits and either:
  1002. // we have an integer, so there is no fractional stuff to
  1003. // display, or we're out of significant digits.
  1004. if (i >= minFraDigits &&
  1005. (isInteger || digitIndex >= digitList.count)) {
  1006. break;
  1007. }
  1008. // Output leading fractional zeros. These are zeros that come
  1009. // after the decimal but before any significant digits. These
  1010. // are only output if abs(number being formatted) < 1.0.
  1011. if (-1-i > (digitList.decimalAt-1)) {
  1012. result.append(zero);
  1013. continue;
  1014. }
  1015. // Output a digit, if we have any precision left, or a
  1016. // zero if we don't. We don't want to output noise digits.
  1017. if (!isInteger && digitIndex < digitList.count) {
  1018. result.append((char)(digitList.digits[digitIndex++] + zeroDelta));
  1019. } else {
  1020. result.append(zero);
  1021. }
  1022. }
  1023. // Record field information for caller.
  1024. delegate.formatted(FRACTION_FIELD, Field.FRACTION, Field.FRACTION,
  1025. fFieldStart, result.length(), result);
  1026. }
  1027. if (isNegative) {
  1028. append(result, negativeSuffix, delegate,
  1029. getNegativeSuffixFieldPositions(), Field.SIGN);
  1030. }
  1031. else {
  1032. append(result, positiveSuffix, delegate,
  1033. getPositiveSuffixFieldPositions(), Field.SIGN);
  1034. }
  1035. return result;
  1036. }
  1037. /**
  1038. * Appends the String <code>string</code> to <code>result</code>.
  1039. * <code>delegate</code> is notified of all the
  1040. * <code>FieldPosition</code>s in <code>positions</code>.
  1041. * <p>
  1042. * If one of the <code>FieldPosition</code>s in <code>positions</code>
  1043. * identifies a <code>SIGN</code> attribute, it is mapped to
  1044. * <code>signAttribute</code>. This is used
  1045. * to map the <code>SIGN</code> attribute to the <code>EXPONENT</code>
  1046. * attribute as necessary.
  1047. * <p>
  1048. * This is used by <code>subformat</code> to add the prefix/suffix.
  1049. */
  1050. private void append(StringBuffer result, String string,
  1051. FieldDelegate delegate,
  1052. FieldPosition[] positions,
  1053. Format.Field signAttribute) {
  1054. int start = result.length();
  1055. if (string.length() > 0) {
  1056. result.append(string);
  1057. for (int counter = 0, max = positions.length; counter < max;
  1058. counter++) {
  1059. FieldPosition fp = positions[counter];
  1060. Format.Field attribute = fp.getFieldAttribute();
  1061. if (attribute == Field.SIGN) {
  1062. attribute = signAttribute;
  1063. }
  1064. delegate.formatted(attribute, attribute,
  1065. start + fp.getBeginIndex(),
  1066. start + fp.getEndIndex(), result);
  1067. }
  1068. }
  1069. }
  1070. /**
  1071. * Parses text from a string to produce a <code>Number</code>.
  1072. * <p>
  1073. * The method attempts to parse text starting at the index given by
  1074. * <code>pos</code>.
  1075. * If parsing succeeds, then the index of <code>pos</code> is updated
  1076. * to the index after the last character used (parsing does not necessarily
  1077. * use all characters up to the end of the string), and the parsed
  1078. * number is returned. The updated <code>pos</code> can be used to
  1079. * indicate the starting point for the next call to this method.
  1080. * If an error occurs, then the index of <code>pos</code> is not
  1081. * changed, the error index of <code>pos</code> is set to the index of
  1082. * the character where the error occurred, and null is returned.
  1083. * <p>
  1084. * The subclass returned depends on the value of {@link #isParseBigDecimal}
  1085. * as well as on the string being parsed.
  1086. * <ul>
  1087. * <li>If <code>isParseBigDecimal()</code> is false (the default),
  1088. * most integer values are returned as <code>Long</code>
  1089. * objects, no matter how they are written: <code>"17"</code> and
  1090. * <code>"17.000"</code> both parse to <code>Long(17)</code>.
  1091. * Values that cannot fit into a <code>Long</code> are returned as
  1092. * <code>Double</code>s. This includes values with a fractional part,
  1093. * infinite values, <code>NaN</code>, and the value -0.0.
  1094. * <code>DecimalFormat</code> does <em>not</em> decide whether to
  1095. * return a <code>Double</code> or a <code>Long</code> based on the
  1096. * presence of a decimal separator in the source string. Doing so
  1097. * would prevent integers that overflow the mantissa of a double,
  1098. * such as <code>"-9,223,372,036,854,775,808.00"</code>, from being
  1099. * parsed accurately.
  1100. * <p>
  1101. * Callers may use the <code>Number</code> methods
  1102. * <code>doubleValue</code>, <code>longValue</code>, etc., to obtain
  1103. * the type they want.
  1104. * <li>If <code>isParseBigDecimal()</code> is true, values are returned
  1105. * as <code>BigDecimal</code> objects. The values are the ones
  1106. * constructed by {@link java.math.BigDecimal#BigDecimal(String)}
  1107. * for corresponding strings in locale-independent format. The
  1108. * special cases negative and positive infinity and NaN are returned
  1109. * as <code>Double</code> instances holding the values of the
  1110. * corresponding <code>Double</code> constants.
  1111. * </ul>
  1112. * <p>
  1113. * <code>DecimalFormat</code> parses all Unicode characters that represent
  1114. * decimal digits, as defined by <code>Character.digit()</code>. In
  1115. * addition, <code>DecimalFormat</code> also recognizes as digits the ten
  1116. * consecutive characters starting with the localized zero digit defined in
  1117. * the <code>DecimalFormatSymbols</code> object.
  1118. *
  1119. * @param text the string to be parsed
  1120. * @param pos A <code>ParsePosition</code> object with index and error
  1121. * index information as described above.
  1122. * @return the parsed value, or <code>null</code> if the parse fails
  1123. * @exception NullPointerException if <code>text</code> or
  1124. * <code>pos</code> is null.
  1125. */
  1126. public Number parse(String text, ParsePosition pos) {
  1127. // special case NaN
  1128. if (text.regionMatches(pos.index, symbols.getNaN(), 0, symbols.getNaN().length())) {
  1129. pos.index = pos.index + symbols.getNaN().length();
  1130. return new Double(Double.NaN);
  1131. }
  1132. boolean[] status = new boolean[STATUS_LENGTH];
  1133. if (!subparse(text, pos, positivePrefix, negativePrefix, digitList, false, status)) {
  1134. return null;
  1135. }
  1136. // special case INFINITY
  1137. if (status[STATUS_INFINITE]) {
  1138. if (status[STATUS_POSITIVE] == (multiplier >= 0)) {
  1139. return new Double(Double.POSITIVE_INFINITY);
  1140. } else {
  1141. return new Double(Double.NEGATIVE_INFINITY);
  1142. }
  1143. }
  1144. if (multiplier == 0) {
  1145. if (digitList.isZero()) {
  1146. return new Double(Double.NaN);
  1147. } else if (status[STATUS_POSITIVE]) {
  1148. return new Double(Double.POSITIVE_INFINITY);
  1149. } else {
  1150. return new Double(Double.NEGATIVE_INFINITY);
  1151. }
  1152. }
  1153. if (isParseBigDecimal()) {
  1154. BigDecimal bigDecimalResult = digitList.getBigDecimal();
  1155. if (multiplier != 1) {
  1156. try {
  1157. bigDecimalResult = bigDecimalResult.divide(getBigDecimalMultiplier());
  1158. }
  1159. catch (ArithmeticException e) { // non-terminating decimal expansion
  1160. bigDecimalResult = bigDecimalResult.divide(getBigDecimalMultiplier(), BigDecimal.ROUND_HALF_EVEN);
  1161. }
  1162. }
  1163. if (!status[STATUS_POSITIVE]) {
  1164. bigDecimalResult = bigDecimalResult.negate();
  1165. }
  1166. return bigDecimalResult;
  1167. } else {
  1168. boolean gotDouble = true;
  1169. boolean gotLongMinimum = false;
  1170. double doubleResult = 0.0;
  1171. long longResult = 0;
  1172. // Finally, have DigitList parse the digits into a value.
  1173. if (digitList.fitsIntoLong(status[STATUS_POSITIVE], isParseIntegerOnly())) {
  1174. gotDouble = false;
  1175. longResult = digitList.getLong();
  1176. if (longResult < 0) { // got Long.MIN_VALUE
  1177. gotLongMinimum = true;
  1178. }
  1179. } else {
  1180. doubleResult = digitList.getDouble();
  1181. }
  1182. // Divide by multiplier. We have to be careful here not to do
  1183. // unneeded conversions between double and long.
  1184. if (multiplier != 1) {
  1185. if (gotDouble) {
  1186. doubleResult /= multiplier;
  1187. } else {
  1188. // Avoid converting to double if we can
  1189. if (longResult % multiplier == 0) {
  1190. longResult /= multiplier;
  1191. } else {
  1192. doubleResult = ((double)longResult) / multiplier;
  1193. gotDouble = true;
  1194. }
  1195. }
  1196. }
  1197. if (!status[STATUS_POSITIVE] && !gotLongMinimum) {
  1198. doubleResult = -doubleResult;
  1199. longResult = -longResult;
  1200. }
  1201. // At this point, if we divided the result by the multiplier, the
  1202. // result may fit into a long. We check for this case and return
  1203. // a long if possible.
  1204. // We must do this AFTER applying the negative (if appropriate)
  1205. // in order to handle the case of LONG_MIN; otherwise, if we do
  1206. // this with a positive value -LONG_MIN, the double is > 0, but
  1207. // the long is < 0. We also must retain a double in the case of
  1208. // -0.0, which will compare as == to a long 0 cast to a double
  1209. // (bug 4162852).
  1210. if (multiplier != 1 && gotDouble) {
  1211. longResult = (long)doubleResult;
  1212. gotDouble = ((doubleResult != (double)longResult) ||
  1213. (doubleResult == 0.0 && 1/doubleResult < 0.0)) &&
  1214. !isParseIntegerOnly();
  1215. }
  1216. return gotDouble ?
  1217. (Number)new Double(doubleResult) : (Number)new Long(longResult);
  1218. }
  1219. }
  1220. /**
  1221. * Return a BigInteger multiplier.
  1222. */
  1223. private BigInteger getBigIntegerMultiplier() {
  1224. if (bigIntegerMultiplier == null) {
  1225. bigIntegerMultiplier = BigInteger.valueOf(multiplier);
  1226. }
  1227. return bigIntegerMultiplier;
  1228. }
  1229. private transient BigInteger bigIntegerMultiplier;
  1230. /**
  1231. * Return a BigDecimal multiplier.
  1232. */
  1233. private BigDecimal getBigDecimalMultiplier() {
  1234. if (bigDecimalMultiplier == null) {
  1235. bigDecimalMultiplier = new BigDecimal(multiplier);
  1236. }
  1237. return bigDecimalMultiplier;
  1238. }
  1239. private transient BigDecimal bigDecimalMultiplier;
  1240. private static final int STATUS_INFINITE = 0;
  1241. private static final int STATUS_POSITIVE = 1;
  1242. private static final int STATUS_LENGTH = 2;
  1243. /**
  1244. * Parse the given text into a number. The text is parsed beginning at
  1245. * parsePosition, until an unparseable character is seen.
  1246. * @param text The string to parse.
  1247. * @param parsePosition The position at which to being parsing. Upon
  1248. * return, the first unparseable character.
  1249. * @param digits The DigitList to set to the parsed value.
  1250. * @param isExponent If true, parse an exponent. This means no
  1251. * infinite values and integer only.
  1252. * @param status Upon return contains boolean status flags indicating
  1253. * whether the value was infinite and whether it was positive.
  1254. */
  1255. private final boolean subparse(String text, ParsePosition parsePosition,
  1256. String positivePrefix, String negativePrefix,
  1257. DigitList digits, boolean isExponent,
  1258. boolean status[]) {
  1259. int position = parsePosition.index;
  1260. int oldStart = parsePosition.index;
  1261. int backup;
  1262. boolean gotPositive, gotNegative;
  1263. // check for positivePrefix; take longest
  1264. gotPositive = text.regionMatches(position, positivePrefix, 0,
  1265. positivePrefix.length());
  1266. gotNegative = text.regionMatches(position, negativePrefix, 0,
  1267. negativePrefix.length());
  1268. if (gotPositive && gotNegative) {
  1269. if (positivePrefix.length() > negativePrefix.length()) {
  1270. gotNegative = false;
  1271. } else if (positivePrefix.length() < negativePrefix.length()) {
  1272. gotPositive = false;
  1273. }
  1274. }
  1275. if (gotPositive) {
  1276. position += positivePrefix.length();
  1277. } else if (gotNegative) {
  1278. position += negativePrefix.length();
  1279. } else {
  1280. parsePosition.errorIndex = position;
  1281. return false;
  1282. }
  1283. // process digits or Inf, find decimal position
  1284. status[STATUS_INFINITE] = false;
  1285. if (!isExponent && text.regionMatches(position,symbols.getInfinity(),0,
  1286. symbols.getInfinity().length())) {
  1287. position += symbols.getInfinity().length();
  1288. status[STATUS_INFINITE] = true;
  1289. } else {
  1290. // We now have a string of digits, possibly with grouping symbols,
  1291. // and decimal points. We want to process these into a DigitList.
  1292. // We don't want to put a bunch of leading zeros into the DigitList
  1293. // though, so we keep track of the location of the decimal point,
  1294. // put only significant digits into the DigitList, and adjust the
  1295. // exponent as needed.
  1296. digits.decimalAt = digits.count = 0;
  1297. char zero = symbols.getZeroDigit();
  1298. char decimal = isCurrencyFormat ?
  1299. symbols.getMonetaryDecimalSeparator() :
  1300. symbols.getDecimalSeparator();
  1301. char grouping = symbols.getGroupingSeparator();
  1302. char exponentChar = symbols.getExponentialSymbol();
  1303. boolean sawDecimal = false;
  1304. boolean sawExponent = false;
  1305. boolean sawDigit = false;
  1306. int exponent = 0; // Set to the exponent value, if any
  1307. // We have to track digitCount ourselves, because digits.count will
  1308. // pin when the maximum allowable digits is reached.
  1309. int digitCount = 0;
  1310. backup = -1;
  1311. for (; position < text.length(); ++position) {
  1312. char ch = text.charAt(position);
  1313. /* We recognize all digit ranges, not only the Latin digit range
  1314. * '0'..'9'. We do so by using the Character.digit() method,
  1315. * which converts a valid Unicode digit to the range 0..9.
  1316. *
  1317. * The character 'ch' may be a digit. If so, place its value
  1318. * from 0 to 9 in 'digit'. First try using the locale digit,
  1319. * which may or MAY NOT be a standard Unicode digit range. If
  1320. * this fails, try using the standard Unicode digit ranges by
  1321. * calling Character.digit(). If this also fails, digit will
  1322. * have a value outside the range 0..9.
  1323. */
  1324. int digit = ch - zero;
  1325. if (digit < 0 || digit > 9) {
  1326. digit = Character.digit(ch, 10);
  1327. }
  1328. if (digit == 0) {
  1329. // Cancel out backup setting (see grouping handler below)
  1330. backup = -1; // Do this BEFORE continue statement below!!!
  1331. sawDigit = true;
  1332. // Handle leading zeros
  1333. if (digits.count == 0) {
  1334. // Ignore leading zeros in integer part of number.
  1335. if (!sawDecimal) {
  1336. continue;
  1337. }
  1338. // If we have seen the decimal, but no significant
  1339. // digits yet, then we account for leading zeros by
  1340. // decrementing the digits.decimalAt into negative