1. /*
  2. * @(#)DigitList.java 1.30 03/12/19
  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.math.BigDecimal;
  21. import java.math.BigInteger;
  22. /**
  23. * Digit List. Private to DecimalFormat.
  24. * Handles the transcoding
  25. * between numeric values and strings of characters. Only handles
  26. * non-negative numbers. The division of labor between DigitList and
  27. * DecimalFormat is that DigitList handles the radix 10 representation
  28. * issues; DecimalFormat handles the locale-specific issues such as
  29. * positive/negative, grouping, decimal point, currency, and so on.
  30. *
  31. * A DigitList is really a representation of a floating point value.
  32. * It may be an integer value; we assume that a double has sufficient
  33. * precision to represent all digits of a long.
  34. *
  35. * The DigitList representation consists of a string of characters,
  36. * which are the digits radix 10, from '0' to '9'. It also has a radix
  37. * 10 exponent associated with it. The value represented by a DigitList
  38. * object can be computed by mulitplying the fraction f, where 0 <= f < 1,
  39. * derived by placing all the digits of the list to the right of the
  40. * decimal point, by 10^exponent.
  41. *
  42. * @see Locale
  43. * @see Format
  44. * @see NumberFormat
  45. * @see DecimalFormat
  46. * @see ChoiceFormat
  47. * @see MessageFormat
  48. * @version 1.30 12/19/03
  49. * @author Mark Davis, Alan Liu
  50. */
  51. final class DigitList implements Cloneable {
  52. /**
  53. * The maximum number of significant digits in an IEEE 754 double, that
  54. * is, in a Java double. This must not be increased, or garbage digits
  55. * will be generated, and should not be decreased, or accuracy will be lost.
  56. */
  57. public static final int MAX_COUNT = 19; // == Long.toString(Long.MAX_VALUE).length()
  58. /**
  59. * These data members are intentionally public and can be set directly.
  60. *
  61. * The value represented is given by placing the decimal point before
  62. * digits[decimalAt]. If decimalAt is < 0, then leading zeros between
  63. * the decimal point and the first nonzero digit are implied. If decimalAt
  64. * is > count, then trailing zeros between the digits[count-1] and the
  65. * decimal point are implied.
  66. *
  67. * Equivalently, the represented value is given by f * 10^decimalAt. Here
  68. * f is a value 0.1 <= f < 1 arrived at by placing the digits in Digits to
  69. * the right of the decimal.
  70. *
  71. * DigitList is normalized, so if it is non-zero, figits[0] is non-zero. We
  72. * don't allow denormalized numbers because our exponent is effectively of
  73. * unlimited magnitude. The count value contains the number of significant
  74. * digits present in digits[].
  75. *
  76. * Zero is represented by any DigitList with count == 0 or with each digits[i]
  77. * for all i <= count == '0'.
  78. */
  79. public int decimalAt = 0;
  80. public int count = 0;
  81. public char[] digits = new char[MAX_COUNT];
  82. private char[] data;
  83. /**
  84. * Return true if the represented number is zero.
  85. */
  86. boolean isZero() {
  87. for (int i=0; i < count; ++i) {
  88. if (digits[i] != '0') {
  89. return false;
  90. }
  91. }
  92. return true;
  93. }
  94. /**
  95. * Clears out the digits.
  96. * Use before appending them.
  97. * Typically, you set a series of digits with append, then at the point
  98. * you hit the decimal point, you set myDigitList.decimalAt = myDigitList.count;
  99. * then go on appending digits.
  100. */
  101. public void clear () {
  102. decimalAt = 0;
  103. count = 0;
  104. }
  105. /**
  106. * Appends a digit to the list, extending the list when necessary.
  107. */
  108. public void append(char digit) {
  109. if (count == digits.length) {
  110. char[] data = new char[count + 100];
  111. System.arraycopy(digits, 0, data, 0, count);
  112. digits = data;
  113. }
  114. digits[count++] = digit;
  115. }
  116. /**
  117. * Utility routine to get the value of the digit list
  118. * If (count == 0) this throws a NumberFormatException, which
  119. * mimics Long.parseLong().
  120. */
  121. public final double getDouble() {
  122. if (count == 0) {
  123. return 0.0;
  124. }
  125. StringBuffer temp = getStringBuffer();
  126. temp.append('.');
  127. temp.append(digits, 0, count);
  128. temp.append('E');
  129. temp.append(decimalAt);
  130. return Double.parseDouble(temp.toString());
  131. }
  132. /**
  133. * Utility routine to get the value of the digit list.
  134. * If (count == 0) this returns 0, unlike Long.parseLong().
  135. */
  136. public final long getLong() {
  137. // for now, simple implementation; later, do proper IEEE native stuff
  138. if (count == 0) {
  139. return 0;
  140. }
  141. // We have to check for this, because this is the one NEGATIVE value
  142. // we represent. If we tried to just pass the digits off to parseLong,
  143. // we'd get a parse failure.
  144. if (isLongMIN_VALUE()) {
  145. return Long.MIN_VALUE;
  146. }
  147. StringBuffer temp = getStringBuffer();
  148. temp.append(digits, 0, count);
  149. for (int i = count; i < decimalAt; ++i) {
  150. temp.append('0');
  151. }
  152. return Long.parseLong(temp.toString());
  153. }
  154. public final BigDecimal getBigDecimal() {
  155. if (count == 0) {
  156. if (decimalAt == 0) {
  157. return BigDecimal.ZERO;
  158. } else {
  159. return new BigDecimal("0E" + decimalAt);
  160. }
  161. }
  162. StringBuffer temp = new StringBuffer(count + 12);
  163. temp.append('.');
  164. temp.append(digits, 0, count);
  165. temp.append('E');
  166. temp.append(decimalAt);
  167. return new BigDecimal(temp.toString());
  168. }
  169. /**
  170. * Return true if the number represented by this object can fit into
  171. * a long.
  172. * @param isPositive true if this number should be regarded as positive
  173. * @param ignoreNegativeZero true if -0 should be regarded as identical to
  174. * +0; otherwise they are considered distinct
  175. * @return true if this number fits into a Java long
  176. */
  177. boolean fitsIntoLong(boolean isPositive, boolean ignoreNegativeZero) {
  178. // Figure out if the result will fit in a long. We have to
  179. // first look for nonzero digits after the decimal point;
  180. // then check the size. If the digit count is 18 or less, then
  181. // the value can definitely be represented as a long. If it is 19
  182. // then it may be too large.
  183. // Trim trailing zeros. This does not change the represented value.
  184. while (count > 0 && digits[count - 1] == '0') {
  185. --count;
  186. }
  187. if (count == 0) {
  188. // Positive zero fits into a long, but negative zero can only
  189. // be represented as a double. - bug 4162852
  190. return isPositive || ignoreNegativeZero;
  191. }
  192. if (decimalAt < count || decimalAt > MAX_COUNT) {
  193. return false;
  194. }
  195. if (decimalAt < MAX_COUNT) return true;
  196. // At this point we have decimalAt == count, and count == MAX_COUNT.
  197. // The number will overflow if it is larger than 9223372036854775807
  198. // or smaller than -9223372036854775808.
  199. for (int i=0; i<count; ++i) {
  200. char dig = digits[i], max = LONG_MIN_REP[i];
  201. if (dig > max) return false;
  202. if (dig < max) return true;
  203. }
  204. // At this point the first count digits match. If decimalAt is less
  205. // than count, then the remaining digits are zero, and we return true.
  206. if (count < decimalAt) return true;
  207. // Now we have a representation of Long.MIN_VALUE, without the leading
  208. // negative sign. If this represents a positive value, then it does
  209. // not fit; otherwise it fits.
  210. return !isPositive;
  211. }
  212. /**
  213. * Set the digit list to a representation of the given double value.
  214. * This method supports fixed-point notation.
  215. * @param source Value to be converted; must not be Inf, -Inf, Nan,
  216. * or a value <= 0.
  217. * @param maximumFractionDigits The most fractional digits which should
  218. * be converted.
  219. */
  220. public final void set(double source, int maximumFractionDigits) {
  221. set(source, maximumFractionDigits, true);
  222. }
  223. /**
  224. * Set the digit list to a representation of the given double value.
  225. * This method supports both fixed-point and exponential notation.
  226. * @param source Value to be converted; must not be Inf, -Inf, Nan,
  227. * or a value <= 0.
  228. * @param maximumDigits The most fractional or total digits which should
  229. * be converted.
  230. * @param fixedPoint If true, then maximumDigits is the maximum
  231. * fractional digits to be converted. If false, total digits.
  232. */
  233. final void set(double source, int maximumDigits, boolean fixedPoint) {
  234. set(Double.toString(source), maximumDigits, fixedPoint);
  235. }
  236. /**
  237. * Generate a representation of the form DDDDD, DDDDD.DDDDD, or
  238. * DDDDDE+/-DDDDD.
  239. */
  240. final void set(String s, int maximumDigits, boolean fixedPoint) {
  241. int len = s.length();
  242. char[] source = getDataChars(len);
  243. s.getChars(0, len, source, 0);
  244. decimalAt = -1;
  245. count = 0;
  246. int exponent = 0;
  247. // Number of zeros between decimal point and first non-zero digit after
  248. // decimal point, for numbers < 1.
  249. int leadingZerosAfterDecimal = 0;
  250. boolean nonZeroDigitSeen = false;
  251. for (int i = 0; i < len; ) {
  252. char c = source[i++];
  253. if (c == '.') {
  254. decimalAt = count;
  255. } else if (c == 'e' || c == 'E') {
  256. exponent = parseInt(source, i, len);
  257. break;
  258. } else {
  259. if (!nonZeroDigitSeen) {
  260. nonZeroDigitSeen = (c != '0');
  261. if (!nonZeroDigitSeen && decimalAt != -1)
  262. ++leadingZerosAfterDecimal;
  263. }
  264. if (nonZeroDigitSeen) {
  265. digits[count++] = c;
  266. }
  267. }
  268. }
  269. if (decimalAt == -1) {
  270. decimalAt = count;
  271. }
  272. if (nonZeroDigitSeen) {
  273. decimalAt += exponent - leadingZerosAfterDecimal;
  274. }
  275. if (fixedPoint) {
  276. // The negative of the exponent represents the number of leading
  277. // zeros between the decimal and the first non-zero digit, for
  278. // a value < 0.1 (e.g., for 0.00123, -decimalAt == 2). If this
  279. // is more than the maximum fraction digits, then we have an underflow
  280. // for the printed representation.
  281. if (-decimalAt > maximumDigits) {
  282. // Handle an underflow to zero when we round something like
  283. // 0.0009 to 2 fractional digits.
  284. count = 0;
  285. return;
  286. } else if (-decimalAt == maximumDigits) {
  287. // If we round 0.0009 to 3 fractional digits, then we have to
  288. // create a new one digit in the least significant location.
  289. if (shouldRoundUp(0)) {
  290. count = 1;
  291. ++decimalAt;
  292. digits[0] = '1';
  293. } else {
  294. count = 0;
  295. }
  296. return;
  297. }
  298. // else fall through
  299. }
  300. // Eliminate trailing zeros.
  301. while (count > 1 && digits[count - 1] == '0') {
  302. --count;
  303. }
  304. // Eliminate digits beyond maximum digits to be displayed.
  305. // Round up if appropriate.
  306. round(fixedPoint ? (maximumDigits + decimalAt) : maximumDigits);
  307. }
  308. /**
  309. * Round the representation to the given number of digits.
  310. * @param maximumDigits The maximum number of digits to be shown.
  311. * Upon return, count will be less than or equal to maximumDigits.
  312. */
  313. private final void round(int maximumDigits) {
  314. // Eliminate digits beyond maximum digits to be displayed.
  315. // Round up if appropriate.
  316. if (maximumDigits >= 0 && maximumDigits < count) {
  317. if (shouldRoundUp(maximumDigits)) {
  318. // Rounding up involved incrementing digits from LSD to MSD.
  319. // In most cases this is simple, but in a worst case situation
  320. // (9999..99) we have to adjust the decimalAt value.
  321. for (;;) {
  322. --maximumDigits;
  323. if (maximumDigits < 0) {
  324. // We have all 9's, so we increment to a single digit
  325. // of one and adjust the exponent.
  326. digits[0] = '1';
  327. ++decimalAt;
  328. maximumDigits = 0; // Adjust the count
  329. break;
  330. }
  331. ++digits[maximumDigits];
  332. if (digits[maximumDigits] <= '9') break;
  333. // digits[maximumDigits] = '0'; // Unnecessary since we'll truncate this
  334. }
  335. ++maximumDigits; // Increment for use as count
  336. }
  337. count = maximumDigits;
  338. // Eliminate trailing zeros.
  339. while (count > 1 && digits[count-1] == '0') {
  340. --count;
  341. }
  342. }
  343. }
  344. /**
  345. * Return true if truncating the representation to the given number
  346. * of digits will result in an increment to the last digit. This
  347. * method implements half-even rounding, the default rounding mode.
  348. * [bnf]
  349. * @param maximumDigits the number of digits to keep, from 0 to
  350. * <code>count-1</code>. If 0, then all digits are rounded away, and
  351. * this method returns true if a one should be generated (e.g., formatting
  352. * 0.09 with "#.#").
  353. * @return true if digit <code>maximumDigits-1</code> should be
  354. * incremented
  355. */
  356. private boolean shouldRoundUp(int maximumDigits) {
  357. boolean increment = false;
  358. // Implement IEEE half-even rounding
  359. if (maximumDigits < count) {
  360. if (digits[maximumDigits] > '5') {
  361. return true;
  362. } else if (digits[maximumDigits] == '5' ) {
  363. for (int i=maximumDigits+1; i<count; ++i) {
  364. if (digits[i] != '0') {
  365. return true;
  366. }
  367. }
  368. return maximumDigits > 0 && (digits[maximumDigits-1] % 2 != 0);
  369. }
  370. }
  371. return false;
  372. }
  373. /**
  374. * Utility routine to set the value of the digit list from a long
  375. */
  376. public final void set(long source) {
  377. set(source, 0);
  378. }
  379. /**
  380. * Set the digit list to a representation of the given long value.
  381. * @param source Value to be converted; must be >= 0 or ==
  382. * Long.MIN_VALUE.
  383. * @param maximumDigits The most digits which should be converted.
  384. * If maximumDigits is lower than the number of significant digits
  385. * in source, the representation will be rounded. Ignored if <= 0.
  386. */
  387. public final void set(long source, int maximumDigits) {
  388. // This method does not expect a negative number. However,
  389. // "source" can be a Long.MIN_VALUE (-9223372036854775808),
  390. // if the number being formatted is a Long.MIN_VALUE. In that
  391. // case, it will be formatted as -Long.MIN_VALUE, a number
  392. // which is outside the legal range of a long, but which can
  393. // be represented by DigitList.
  394. if (source <= 0) {
  395. if (source == Long.MIN_VALUE) {
  396. decimalAt = count = MAX_COUNT;
  397. System.arraycopy(LONG_MIN_REP, 0, digits, 0, count);
  398. } else {
  399. decimalAt = count = 0; // Values <= 0 format as zero
  400. }
  401. } else {
  402. // Rewritten to improve performance. I used to call
  403. // Long.toString(), which was about 4x slower than this code.
  404. int left = MAX_COUNT;
  405. int right;
  406. while (source > 0) {
  407. digits[--left] = (char)('0' + (source % 10));
  408. source /= 10;
  409. }
  410. decimalAt = MAX_COUNT - left;
  411. // Don't copy trailing zeros. We are guaranteed that there is at
  412. // least one non-zero digit, so we don't have to check lower bounds.
  413. for (right = MAX_COUNT - 1; digits[right] == '0'; --right)
  414. ;
  415. count = right - left + 1;
  416. System.arraycopy(digits, left, digits, 0, count);
  417. }
  418. if (maximumDigits > 0) round(maximumDigits);
  419. }
  420. /**
  421. * Set the digit list to a representation of the given BigDecimal value.
  422. * This method supports both fixed-point and exponential notation.
  423. * @param source Value to be converted; must not be a value <= 0.
  424. * @param maximumDigits The most fractional or total digits which should
  425. * be converted.
  426. * @param fixedPoint If true, then maximumDigits is the maximum
  427. * fractional digits to be converted. If false, total digits.
  428. */
  429. final void set(BigDecimal source, int maximumDigits, boolean fixedPoint) {
  430. String s = source.toString();
  431. extendDigits(s.length());
  432. set(s, maximumDigits, fixedPoint);
  433. }
  434. /**
  435. * Set the digit list to a representation of the given BigInteger value.
  436. * @param source Value to be converted; must be >= 0.
  437. * @param maximumDigits The most digits which should be converted.
  438. * If maximumDigits is lower than the number of significant digits
  439. * in source, the representation will be rounded. Ignored if <= 0.
  440. */
  441. final void set(BigInteger source, int maximumDigits) {
  442. String s = source.toString();
  443. int len = s.length();
  444. extendDigits(len);
  445. s.getChars(0, len, digits, 0);
  446. decimalAt = len;
  447. int right;
  448. for (right = len - 1; right >= 0 && digits[right] == '0'; --right)
  449. ;
  450. count = right + 1;
  451. if (maximumDigits > 0) {
  452. round(maximumDigits);
  453. }
  454. }
  455. /**
  456. * equality test between two digit lists.
  457. */
  458. public boolean equals(Object obj) {
  459. if (this == obj) // quick check
  460. return true;
  461. if (!(obj instanceof DigitList)) // (1) same object?
  462. return false;
  463. DigitList other = (DigitList) obj;
  464. if (count != other.count ||
  465. decimalAt != other.decimalAt)
  466. return false;
  467. for (int i = 0; i < count; i++)
  468. if (digits[i] != other.digits[i])
  469. return false;
  470. return true;
  471. }
  472. /**
  473. * Generates the hash code for the digit list.
  474. */
  475. public int hashCode() {
  476. int hashcode = decimalAt;
  477. for (int i = 0; i < count; i++) {
  478. hashcode = hashcode * 37 + digits[i];
  479. }
  480. return hashcode;
  481. }
  482. /**
  483. * Creates a copy of this object.
  484. * @return a clone of this instance.
  485. */
  486. public Object clone() {
  487. try {
  488. DigitList other = (DigitList) super.clone();
  489. char[] newDigits = new char[digits.length];
  490. System.arraycopy(digits, 0, newDigits, 0, digits.length);
  491. other.digits = newDigits;
  492. return other;
  493. } catch (CloneNotSupportedException e) {
  494. throw new InternalError();
  495. }
  496. }
  497. /**
  498. * Returns true if this DigitList represents Long.MIN_VALUE;
  499. * false, otherwise. This is required so that getLong() works.
  500. */
  501. private boolean isLongMIN_VALUE() {
  502. if (decimalAt != count || count != MAX_COUNT) {
  503. return false;
  504. }
  505. for (int i = 0; i < count; ++i) {
  506. if (digits[i] != LONG_MIN_REP[i]) return false;
  507. }
  508. return true;
  509. }
  510. private static final int parseInt(char[] str, int offset, int strLen) {
  511. char c;
  512. boolean positive = true;
  513. if ((c = str[offset]) == '-') {
  514. positive = false;
  515. offset++;
  516. } else if (c == '+') {
  517. offset++;
  518. }
  519. int value = 0;
  520. while (offset < strLen) {
  521. c = str[offset++];
  522. if (c >= '0' && c <= '9') {
  523. value = value * 10 + (c - '0');
  524. } else {
  525. break;
  526. }
  527. }
  528. return positive ? value : -value;
  529. }
  530. // The digit part of -9223372036854775808L
  531. private static final char[] LONG_MIN_REP = "9223372036854775808".toCharArray();
  532. public String toString() {
  533. if (isZero()) {
  534. return "0";
  535. }
  536. StringBuffer buf = getStringBuffer();
  537. buf.append("0.");
  538. buf.append(digits, 0, count);
  539. buf.append("x10^");
  540. buf.append(decimalAt);
  541. return buf.toString();
  542. }
  543. private StringBuffer tempBuffer;
  544. private StringBuffer getStringBuffer() {
  545. if (tempBuffer == null) {
  546. tempBuffer = new StringBuffer(MAX_COUNT);
  547. } else {
  548. tempBuffer.setLength(0);
  549. }
  550. return tempBuffer;
  551. }
  552. private void extendDigits(int len) {
  553. if (len > digits.length) {
  554. digits = new char[len];
  555. }
  556. }
  557. private final char[] getDataChars(int length) {
  558. if (data == null || data.length < length) {
  559. data = new char[length];
  560. }
  561. return data;
  562. }
  563. }