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