1. /*
  2. * Copyright 2003 Sun Microsystems, Inc. All rights reserved.
  3. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  4. */
  5. /*
  6. * @(#)BigDecimal.java 1.42 03/01/23
  7. */
  8. package java.math;
  9. /**
  10. * Immutable, arbitrary-precision signed decimal numbers. A BigDecimal
  11. * consists of an arbitrary precision integer <i>unscaled value</i> and a
  12. * non-negative 32-bit integer <i>scale</i>, which represents the number of
  13. * digits to the right of the decimal point. The number represented by the
  14. * BigDecimal is <tt>(unscaledValue/10<sup>scale</sup>)</tt>. BigDecimal
  15. * provides operations for basic arithmetic, scale manipulation, comparison,
  16. * hashing, and format conversion.
  17. * <p>
  18. * The BigDecimal class gives its user complete control over rounding
  19. * behavior, forcing the user to explicitly specify a rounding
  20. * behavior for operations capable of discarding precision ({@link
  21. * #divide(BigDecimal, int)}, {@link #divide(BigDecimal, int, int)},
  22. * and {@link #setScale}). Eight <em>rounding modes</em> are provided
  23. * for this purpose.
  24. * <p>
  25. * Two types of operations are provided for manipulating the scale of a
  26. * BigDecimal: scaling/rounding operations and decimal point motion
  27. * operations. Scaling/rounding operations (<tt>setScale</tt>) return a
  28. * BigDecimal whose value is approximately (or exactly) equal to that of the
  29. * operand, but whose scale is the specified value; that is, they increase or
  30. * decrease the precision of the number with minimal effect on its value.
  31. * Decimal point motion operations ({@link #movePointLeft} and
  32. * {@link #movePointRight}) return a BigDecimal created from the operand by
  33. * moving the decimal point a specified distance in the specified direction;
  34. * that is, they change a number's value without affecting its precision.
  35. * <p>
  36. * For the sake of brevity and clarity, pseudo-code is used throughout the
  37. * descriptions of BigDecimal methods. The pseudo-code expression
  38. * <tt>(i + j)</tt> is shorthand for "a BigDecimal whose value is
  39. * that of the BigDecimal <tt>i</tt> plus that of the BigDecimal <tt>j</tt>."
  40. * The pseudo-code expression <tt>(i == j)</tt> is shorthand for
  41. * "<tt>true</tt> if and only if the BigDecimal <tt>i</tt> represents the same
  42. * value as the the BigDecimal <tt>j</tt>." Other pseudo-code expressions are
  43. * interpreted similarly.
  44. * <p>
  45. * Note: care should be exercised if BigDecimals are to be used as
  46. * keys in a {@link java.util.SortedMap} or elements in a {@link
  47. * java.util.SortedSet}, as BigDecimal's <i>natural ordering</i> is
  48. * <i>inconsistent with equals</i>. See {@link Comparable}, {@link
  49. * java.util.SortedMap} or {@link java.util.SortedSet} for more
  50. * information.
  51. * <p>
  52. * All methods and constructors for this class
  53. * throw <CODE>NullPointerException</CODE> when passed
  54. * a null object reference for any input parameter.
  55. *
  56. * @see BigInteger
  57. * @see java.util.SortedMap
  58. * @see java.util.SortedSet
  59. * @version 1.42, 01/23/03
  60. * @author Josh Bloch
  61. */
  62. public class BigDecimal extends Number implements Comparable {
  63. /**
  64. * The unscaled value of this BigDecimal, as returned by unscaledValue().
  65. *
  66. * @serial
  67. * @see #unscaledValue
  68. */
  69. private BigInteger intVal;
  70. /**
  71. * The scale of this BigDecimal, as returned by scale().
  72. *
  73. * @serial
  74. * @see #scale
  75. */
  76. private int scale = 0;
  77. /* Appease the serialization gods */
  78. private static final long serialVersionUID = 6108874887143696463L;
  79. // Constructors
  80. /**
  81. * Translates the String representation of a BigDecimal into a
  82. * BigDecimal. The String representation consists of an optional
  83. * sign, <tt>'+'</tt> (<tt>'\u002B'</tt>) or <tt>'-'</tt>
  84. * (<tt>'\u002D'</tt>), followed by a sequence of zero or more
  85. * decimal digits ("the integer"), optionally followed by a
  86. * fraction, optionally followed by an exponent.
  87. *
  88. * <p>The fraction consists of of a decimal point followed by zero or more
  89. * decimal digits. The string must contain at least one digit in either
  90. * the integer or the fraction. The number formed by the sign, the
  91. * integer and the fraction is referred to as the <i>significand</i>.
  92. *
  93. * <p>The exponent consists of the character <tt>'e'</tt>
  94. * (<tt>'\u0075'</tt>) or <tt>'E'</tt> (<tt>'\u0045'</tt>)
  95. * followed by one or more decimal digits. The value of the
  96. * exponent must lie between -{@link Integer#MAX_VALUE} ({@link
  97. * Integer#MIN_VALUE}+1) and {@link Integer#MAX_VALUE}, inclusive.
  98. *
  99. * <p>More formally, the strings this constructor accepts are
  100. * described by the following grammar:
  101. * <blockquote>
  102. * <dl>
  103. * <dt><i>BigDecimalString:</i>
  104. * <dd><i>Sign<sub>opt</sub> Significand Exponent<sub>opt</sub></i>
  105. * <p>
  106. * <dt><i>Sign:</i>
  107. * <dd><code>+</code>
  108. * <dd><code>-</code>
  109. * <p>
  110. * <dt><i>Significand:</i>
  111. * <dd><i>IntegerPart</i> <code>.</code> <i>FractionPart<sub>opt</sub></i>
  112. * <dd><code>.</code> <i>FractionPart</i>
  113. * <dd><i>IntegerPart</i>
  114. * <p>
  115. * <dt><i>IntegerPart:
  116. * <dd>Digits</i>
  117. * <p>
  118. * <dt><i>FractionPart:
  119. * <dd>Digits</i>
  120. * <p>
  121. * <dt><i>Exponent:
  122. * <dd>ExponentIndicator SignedInteger</i>
  123. * <p>
  124. * <dt><i>ExponentIndicator:</i>
  125. * <dd><code>e</code>
  126. * <dd><code>E</code>
  127. * <p>
  128. * <dt><i>SignedInteger:
  129. * <dd>Sign<sub>opt</sub> Digits</i>
  130. * <p>
  131. * <dt><i>Digits:
  132. * <dd>Digit
  133. * <dd>Digits Digit</i>
  134. * <p>
  135. * <dt><i>Digit:</i>
  136. * <dd>any character for which {@link Character#isDigit}
  137. * returns <code>true</code>, including 0, 1, 2 ...
  138. * </dl>
  139. * </blockquote>
  140. *
  141. * <p>The scale of the returned BigDecimal will be the number of digits in
  142. * the fraction, or zero if the string contains no decimal point, subject
  143. * to adjustment for any exponent: If the string contains an exponent, the
  144. * exponent is subtracted from the scale. If the resulting scale is
  145. * negative, the scale of the returned BigDecimal is zero and the unscaled
  146. * value is multiplied by the appropriate power of ten so that, in every
  147. * case, the resulting BigDecimal is equal to <i>significand</i> ×
  148. * 10<i><sup>exponent</sup></i>. (If in the future this specification is
  149. * amended to permit negative scales, the final step of zeroing the scale
  150. * and adjusting the unscaled value will be eliminated.)
  151. *
  152. * <p>The character-to-digit mapping is provided by {@link
  153. * java.lang.Character#digit} set to convert to radix 10. The
  154. * String may not contain any extraneous characters (whitespace,
  155. * for example).
  156. *
  157. * <p>Note: For values other <tt>float</tt> and <tt>double</tt>
  158. * NaN and ±Infinity, this constructor is compatible with
  159. * the values returned by {@link Float#toString} and {@link
  160. * Double#toString}. This is generally the preferred way to
  161. * convert a <tt>float</tt> or <tt>double</tt> into a BigDecimal,
  162. * as it doesn't suffer from the unpredictability of the {@link
  163. * #BigDecimal(double)} constructor.
  164. *
  165. * <p>Note: the optional leading plus sign and trailing exponent were
  166. * added in release 1.3.
  167. *
  168. * @param val String representation of BigDecimal.
  169. * @throws NumberFormatException <tt>val</tt> is not a valid representation
  170. * of a BigDecimal.
  171. */
  172. public BigDecimal(String val) {
  173. // Empty string not accepted
  174. if (val.length() == 0)
  175. throw new NumberFormatException();
  176. // Deal with leading plus sign if present
  177. if (val.charAt(0) == '+') {
  178. val = val.substring(1); /* Discard leading '+' */
  179. if (val.length() == 0 || /* "+" illegal! */
  180. val.charAt(0) == '-') /* "+-123.456" illegal! */
  181. throw new NumberFormatException();
  182. }
  183. // If exponent is present, break into exponent and significand
  184. int exponent = 0;
  185. int ePos = val.indexOf('e');
  186. if (ePos == -1)
  187. ePos = val.indexOf('E');
  188. if (ePos != -1) {
  189. String exp = val.substring(ePos+1);
  190. if (exp.length() == 0) /* "1.2e" illegal! */
  191. throw new NumberFormatException();
  192. if (exp.charAt(0) == '+') {
  193. exp = exp.substring(1); /* Discard leading '+' */
  194. if (exp.length() == 0 || /* "123.456e+" illegal! */
  195. exp.charAt(0) == '-') /* "123.456e+-7" illegal! */
  196. throw new NumberFormatException();
  197. }
  198. exponent = Integer.parseInt(exp);
  199. if (ePos==0)
  200. throw new NumberFormatException(); /* "e123" illegal! */
  201. val = val.substring(0, ePos);
  202. }
  203. // Parse significand
  204. int pointPos = val.indexOf('.');
  205. if (pointPos == -1) { /* e.g. "123" */
  206. intVal = new BigInteger(val);
  207. } else if (pointPos == val.length()-1) { /* e.g. "123." */
  208. intVal = new BigInteger(val.substring(0, val.length()-1));
  209. } else { /* Fraction part exists */
  210. if (val.charAt(pointPos+1) == '-') /* ".-123" illegal! */
  211. throw new NumberFormatException();
  212. char[] digits = new char[val.length()-1];
  213. // Get chars before decimal point
  214. val.getChars(0, pointPos, digits, 0);
  215. // Get chars after decimal point
  216. val.getChars(pointPos+1, val.length(), digits, pointPos);
  217. scale = val.length() - pointPos - 1;
  218. intVal = new BigInteger(digits);
  219. }
  220. // Combine exponent into significand
  221. assert (scale >= 0); // && scale <= Integer.MAX_VALUE
  222. long longScale = (long)scale - (long)exponent; // Avoid errors
  223. // in calculating scale
  224. if(longScale > Integer.MAX_VALUE)
  225. throw new NumberFormatException("Final scale out of range");
  226. scale = (int)longScale;
  227. assert (scale == longScale && // conversion should be exact
  228. Math.abs(longScale) <= Integer.MAX_VALUE) // exponent range
  229. // check
  230. :longScale;
  231. if (scale < 0) {
  232. intVal = timesTenToThe(intVal, -scale);
  233. scale = 0;
  234. }
  235. }
  236. /**
  237. * Translates a <code>double</code> into a BigDecimal. The scale
  238. * of the BigDecimal is the smallest value such that
  239. * <tt>(10<sup>scale</sup> * val)</tt> is an integer.
  240. * <p>
  241. * Note: the results of this constructor can be somewhat unpredictable.
  242. * One might assume that <tt>new BigDecimal(.1)</tt> is exactly equal
  243. * to .1, but it is actually equal
  244. * to .1000000000000000055511151231257827021181583404541015625.
  245. * This is so because .1 cannot be represented exactly as a double
  246. * (or, for that matter, as a binary fraction of any finite length).
  247. * Thus, the long value that is being passed <i>in</i> to the constructor
  248. * is not exactly equal to .1, appearances notwithstanding.
  249. * <p>
  250. * The (String) constructor, on the other hand, is perfectly predictable:
  251. * <tt>new BigDecimal(".1")</tt> is <i>exactly</i> equal to .1, as one
  252. * would expect. Therefore, it is generally recommended that the (String)
  253. * constructor be used in preference to this one.
  254. *
  255. * @param val <code>double</code> value to be converted to BigDecimal.
  256. * @throws NumberFormatException <tt>val</tt> if <tt>val</tt> is
  257. * infinite or NaN.
  258. */
  259. public BigDecimal(double val) {
  260. if (Double.isInfinite(val) || Double.isNaN(val))
  261. throw new NumberFormatException("Infinite or NaN");
  262. /*
  263. * Translate the double into sign, exponent and mantissa, according
  264. * to the formulae in JLS, Section 20.10.22.
  265. */
  266. long valBits = Double.doubleToLongBits(val);
  267. int sign = ((valBits >> 63)==0 ? 1 : -1);
  268. int exponent = (int) ((valBits >> 52) & 0x7ffL);
  269. long mantissa = (exponent==0 ? (valBits & ((1L<<52) - 1)) << 1
  270. : (valBits & ((1L<<52) - 1)) | (1L<<52));
  271. exponent -= 1075;
  272. /* At this point, val == sign * mantissa * 2**exponent */
  273. /*
  274. * Special case zero to to supress nonterminating normalization
  275. * and bogus scale calculation.
  276. */
  277. if (mantissa == 0) {
  278. intVal = BigInteger.ZERO;
  279. return;
  280. }
  281. /* Normalize */
  282. while((mantissa & 1) == 0) { /* i.e., Mantissa is even */
  283. mantissa >>= 1;
  284. exponent++;
  285. }
  286. /* Calculate intVal and scale */
  287. intVal = BigInteger.valueOf(sign*mantissa);
  288. if (exponent < 0) {
  289. intVal = intVal.multiply(BigInteger.valueOf(5).pow(-exponent));
  290. scale = -exponent;
  291. } else if (exponent > 0) {
  292. intVal = intVal.multiply(BigInteger.valueOf(2).pow(exponent));
  293. }
  294. }
  295. /**
  296. * Translates a BigInteger into a BigDecimal. The scale of the BigDecimal
  297. * is zero.
  298. *
  299. * @param val BigInteger value to be converted to BigDecimal.
  300. */
  301. public BigDecimal(BigInteger val) {
  302. intVal = val;
  303. }
  304. /**
  305. * Translates a BigInteger unscaled value and an <code>int</code>
  306. * scale into a BigDecimal. The value of the BigDecimal is
  307. * <tt>(unscaledVal/10<sup>scale</sup>)</tt>.
  308. *
  309. * @param unscaledVal unscaled value of the BigDecimal.
  310. * @param scale scale of the BigDecimal.
  311. * @throws NumberFormatException scale is negative
  312. */
  313. public BigDecimal(BigInteger unscaledVal, int scale) {
  314. if (scale < 0)
  315. throw new NumberFormatException("Negative scale");
  316. intVal = unscaledVal;
  317. this.scale = scale;
  318. }
  319. // Static Factory Methods
  320. /**
  321. * Translates a <code>long</code> unscaled value and an
  322. * <code>int</code> scale into a BigDecimal. This "static factory
  323. * method" is provided in preference to a (<code>long</code>,
  324. * <code>int</code>) constructor because it allows for reuse of
  325. * frequently used BigDecimals.
  326. *
  327. * @param unscaledVal unscaled value of the BigDecimal.
  328. * @param scale scale of the BigDecimal.
  329. * @return a BigDecimal whose value is
  330. * <tt>(unscaledVal/10<sup>scale</sup>)</tt>.
  331. */
  332. public static BigDecimal valueOf(long unscaledVal, int scale) {
  333. return new BigDecimal(BigInteger.valueOf(unscaledVal), scale);
  334. }
  335. /**
  336. * Translates a <code>long</code> value into a BigDecimal with a
  337. * scale of zero. This "static factory method" is provided in
  338. * preference to a (<code>long</code>) constructor because it
  339. * allows for reuse of frequently used BigDecimals.
  340. *
  341. * @param val value of the BigDecimal.
  342. * @return a BigDecimal whose value is <tt>val</tt>.
  343. */
  344. public static BigDecimal valueOf(long val) {
  345. return valueOf(val, 0);
  346. }
  347. // Arithmetic Operations
  348. /**
  349. * Returns a BigDecimal whose value is <tt>(this + val)</tt>, and whose
  350. * scale is <tt>max(this.scale(), val.scale())</tt>.
  351. *
  352. * @param val value to be added to this BigDecimal.
  353. * @return <tt>this + val</tt>
  354. */
  355. public BigDecimal add(BigDecimal val){
  356. BigDecimal arg[] = new BigDecimal[2];
  357. arg[0] = this; arg[1] = val;
  358. matchScale(arg);
  359. return new BigDecimal(arg[0].intVal.add(arg[1].intVal), arg[0].scale);
  360. }
  361. /**
  362. * Returns a BigDecimal whose value is <tt>(this - val)</tt>, and whose
  363. * scale is <tt>max(this.scale(), val.scale())</tt>.
  364. *
  365. * @param val value to be subtracted from this BigDecimal.
  366. * @return <tt>this - val</tt>
  367. */
  368. public BigDecimal subtract(BigDecimal val){
  369. BigDecimal arg[] = new BigDecimal[2];
  370. arg[0] = this; arg[1] = val;
  371. matchScale(arg);
  372. return new BigDecimal(arg[0].intVal.subtract(arg[1].intVal),
  373. arg[0].scale);
  374. }
  375. /**
  376. * Returns a BigDecimal whose value is <tt>(this * val)</tt>, and whose
  377. * scale is <tt>(this.scale() + val.scale())</tt>.
  378. *
  379. * @param val value to be multiplied by this BigDecimal.
  380. * @return <tt>this * val</tt>
  381. */
  382. public BigDecimal multiply(BigDecimal val){
  383. return new BigDecimal(intVal.multiply(val.intVal), scale+val.scale);
  384. }
  385. /**
  386. * Returns a BigDecimal whose value is <tt>(this / val)</tt>, and whose
  387. * scale is as specified. If rounding must be performed to generate a
  388. * result with the specified scale, the specified rounding mode is
  389. * applied.
  390. *
  391. * @param val value by which this BigDecimal is to be divided.
  392. * @param scale scale of the BigDecimal quotient to be returned.
  393. * @param roundingMode rounding mode to apply.
  394. * @return <tt>this / val</tt>
  395. * @throws ArithmeticException <tt>val</tt> is zero, <tt>scale</tt> is
  396. * negative, or <tt>roundingMode==ROUND_UNNECESSARY</tt> and
  397. * the specified scale is insufficient to represent the result
  398. * of the division exactly.
  399. * @throws IllegalArgumentException <tt>roundingMode</tt> does not
  400. * represent a valid rounding mode.
  401. * @see #ROUND_UP
  402. * @see #ROUND_DOWN
  403. * @see #ROUND_CEILING
  404. * @see #ROUND_FLOOR
  405. * @see #ROUND_HALF_UP
  406. * @see #ROUND_HALF_DOWN
  407. * @see #ROUND_HALF_EVEN
  408. * @see #ROUND_UNNECESSARY
  409. */
  410. public BigDecimal divide(BigDecimal val, int scale, int roundingMode) {
  411. if (scale < 0)
  412. throw new ArithmeticException("Negative scale");
  413. if (roundingMode < ROUND_UP || roundingMode > ROUND_UNNECESSARY)
  414. throw new IllegalArgumentException("Invalid rounding mode");
  415. /*
  416. * Rescale dividend or divisor (whichever can be "upscaled" to
  417. * produce correctly scaled quotient).
  418. */
  419. BigDecimal dividend, divisor;
  420. if (scale + val.scale >= this.scale) {
  421. dividend = this.setScale(scale + val.scale);
  422. divisor = val;
  423. } else {
  424. dividend = this;
  425. divisor = val.setScale(this.scale - scale);
  426. }
  427. /* Do the division and return result if it's exact */
  428. BigInteger i[] = dividend.intVal.divideAndRemainder(divisor.intVal);
  429. BigInteger q = i[0], r = i[1];
  430. if (r.signum() == 0)
  431. return new BigDecimal(q, scale);
  432. else if (roundingMode == ROUND_UNNECESSARY) /* Rounding prohibited */
  433. throw new ArithmeticException("Rounding necessary");
  434. /* Round as appropriate */
  435. int signum = dividend.signum() * divisor.signum(); /* Sign of result */
  436. boolean increment;
  437. if (roundingMode == ROUND_UP) { /* Away from zero */
  438. increment = true;
  439. } else if (roundingMode == ROUND_DOWN) { /* Towards zero */
  440. increment = false;
  441. } else if (roundingMode == ROUND_CEILING) { /* Towards +infinity */
  442. increment = (signum > 0);
  443. } else if (roundingMode == ROUND_FLOOR) { /* Towards -infinity */
  444. increment = (signum < 0);
  445. } else { /* Remaining modes based on nearest-neighbor determination */
  446. int cmpFracHalf = r.abs().multiply(BigInteger.valueOf(2)).
  447. compareTo(divisor.intVal.abs());
  448. if (cmpFracHalf < 0) { /* We're closer to higher digit */
  449. increment = false;
  450. } else if (cmpFracHalf > 0) { /* We're closer to lower digit */
  451. increment = true;
  452. } else { /* We're dead-center */
  453. if (roundingMode == ROUND_HALF_UP)
  454. increment = true;
  455. else if (roundingMode == ROUND_HALF_DOWN)
  456. increment = false;
  457. else /* roundingMode == ROUND_HALF_EVEN */
  458. increment = q.testBit(0); /* true iff q is odd */
  459. }
  460. }
  461. return (increment
  462. ? new BigDecimal(q.add(BigInteger.valueOf(signum)), scale)
  463. : new BigDecimal(q, scale));
  464. }
  465. /**
  466. * Returns a BigDecimal whose value is <tt>(this / val)</tt>, and whose
  467. * scale is <tt>this.scale()</tt>. If rounding must be performed to
  468. * generate a result with the given scale, the specified rounding mode is
  469. * applied.
  470. *
  471. * @param val value by which this BigDecimal is to be divided.
  472. * @param roundingMode rounding mode to apply.
  473. * @return <tt>this / val</tt>
  474. * @throws ArithmeticException <tt>val==0</tt>, or
  475. * <tt>roundingMode==ROUND_UNNECESSARY</tt> and
  476. * <tt>this.scale()</tt> is insufficient to represent the result
  477. * of the division exactly.
  478. * @throws IllegalArgumentException <tt>roundingMode</tt> does not
  479. * represent a valid rounding mode.
  480. * @see #ROUND_UP
  481. * @see #ROUND_DOWN
  482. * @see #ROUND_CEILING
  483. * @see #ROUND_FLOOR
  484. * @see #ROUND_HALF_UP
  485. * @see #ROUND_HALF_DOWN
  486. * @see #ROUND_HALF_EVEN
  487. * @see #ROUND_UNNECESSARY
  488. */
  489. public BigDecimal divide(BigDecimal val, int roundingMode) {
  490. return this.divide(val, scale, roundingMode);
  491. }
  492. /**
  493. * Returns a BigDecimal whose value is the absolute value of this
  494. * BigDecimal, and whose scale is <tt>this.scale()</tt>.
  495. *
  496. * @return <tt>abs(this)</tt>
  497. */
  498. public BigDecimal abs(){
  499. return (signum() < 0 ? negate() : this);
  500. }
  501. /**
  502. * Returns a BigDecimal whose value is <tt>(-this)</tt>, and whose scale
  503. * is <tt>this.scale()</tt>.
  504. *
  505. * @return <tt>-this</tt>
  506. */
  507. public BigDecimal negate(){
  508. return new BigDecimal(intVal.negate(), scale);
  509. }
  510. /**
  511. * Returns the signum function of this BigDecimal.
  512. *
  513. * @return -1, 0 or 1 as the value of this BigDecimal is negative, zero or
  514. * positive.
  515. */
  516. public int signum(){
  517. return intVal.signum();
  518. }
  519. /**
  520. * Returns the <i>scale</i> of this BigDecimal. (The scale is the number
  521. * of digits to the right of the decimal point.)
  522. *
  523. * @return the scale of this BigDecimal.
  524. */
  525. public int scale() {
  526. return scale;
  527. }
  528. /**
  529. * Returns a BigInteger whose value is the <i>unscaled value</i> of this
  530. * BigDecimal. (Computes <tt>(this * 10<sup>this.scale()</sup>)</tt>.)
  531. *
  532. * @return the unscaled value of this BigDecimal.
  533. * @since 1.2
  534. */
  535. public BigInteger unscaledValue() {
  536. return intVal;
  537. }
  538. // Rounding Modes
  539. /**
  540. * Rounding mode to round away from zero. Always increments the
  541. * digit prior to a non-zero discarded fraction. Note that this rounding
  542. * mode never decreases the magnitude of the calculated value.
  543. */
  544. public final static int ROUND_UP = 0;
  545. /**
  546. * Rounding mode to round towards zero. Never increments the digit
  547. * prior to a discarded fraction (i.e., truncates). Note that this
  548. * rounding mode never increases the magnitude of the calculated value.
  549. */
  550. public final static int ROUND_DOWN = 1;
  551. /**
  552. * Rounding mode to round towards positive infinity. If the
  553. * BigDecimal is positive, behaves as for <tt>ROUND_UP</tt> if negative,
  554. * behaves as for <tt>ROUND_DOWN</tt>. Note that this rounding mode never
  555. * decreases the calculated value.
  556. */
  557. public final static int ROUND_CEILING = 2;
  558. /**
  559. * Rounding mode to round towards negative infinity. If the
  560. * BigDecimal is positive, behave as for <tt>ROUND_DOWN</tt> if negative,
  561. * behave as for <tt>ROUND_UP</tt>. Note that this rounding mode never
  562. * increases the calculated value.
  563. */
  564. public final static int ROUND_FLOOR = 3;
  565. /**
  566. * Rounding mode to round towards "nearest neighbor" unless both
  567. * neighbors are equidistant, in which case round up.
  568. * Behaves as for <tt>ROUND_UP</tt> if the discarded fraction is >= .5;
  569. * otherwise, behaves as for <tt>ROUND_DOWN</tt>. Note that this is the
  570. * rounding mode that most of us were taught in grade school.
  571. */
  572. public final static int ROUND_HALF_UP = 4;
  573. /**
  574. * Rounding mode to round towards "nearest neighbor" unless both
  575. * neighbors are equidistant, in which case round down.
  576. * Behaves as for <tt>ROUND_UP</tt> if the discarded fraction is > .5;
  577. * otherwise, behaves as for <tt>ROUND_DOWN</tt>.
  578. */
  579. public final static int ROUND_HALF_DOWN = 5;
  580. /**
  581. * Rounding mode to round towards the "nearest neighbor" unless both
  582. * neighbors are equidistant, in which case, round towards the even
  583. * neighbor. Behaves as for ROUND_HALF_UP if the digit to the left of the
  584. * discarded fraction is odd; behaves as for ROUND_HALF_DOWN if it's even.
  585. * Note that this is the rounding mode that minimizes cumulative error
  586. * when applied repeatedly over a sequence of calculations.
  587. */
  588. public final static int ROUND_HALF_EVEN = 6;
  589. /**
  590. * Rounding mode to assert that the requested operation has an exact
  591. * result, hence no rounding is necessary. If this rounding mode is
  592. * specified on an operation that yields an inexact result, an
  593. * <tt>ArithmeticException</tt> is thrown.
  594. */
  595. public final static int ROUND_UNNECESSARY = 7;
  596. // Scaling/Rounding Operations
  597. /**
  598. * Returns a BigDecimal whose scale is the specified value, and whose
  599. * unscaled value is determined by multiplying or dividing this
  600. * BigDecimal's unscaled value by the appropriate power of ten to maintain
  601. * its overall value. If the scale is reduced by the operation, the
  602. * unscaled value must be divided (rather than multiplied), and the value
  603. * may be changed; in this case, the specified rounding mode is applied to
  604. * the division.
  605. * <p>
  606. * Note that since BigDecimal objects are immutable, calls of this
  607. * method do <i>not</i> result in the original object being
  608. * modified, contrary to the usual convention of having methods
  609. * named <code>set<i>X</i></code> mutate field
  610. * <code><i>X</i></code>. Instead, <code>setScale</code> returns
  611. * an object with the proper scale; the returned object may or may
  612. * not be newly allocated.
  613. *
  614. * @param scale scale of the BigDecimal value to be returned.
  615. * @param roundingMode The rounding mode to apply.
  616. * @return a BigDecimal whose scale is the specified value, and whose
  617. * unscaled value is determined by multiplying or dividing this
  618. * BigDecimal's unscaled value by the appropriate power of ten to
  619. * maintain its overall value.
  620. * @throws ArithmeticException <tt>scale</tt> is negative, or
  621. * <tt>roundingMode==ROUND_UNNECESSARY</tt> and the specified
  622. * scaling operation would require rounding.
  623. * @throws IllegalArgumentException <tt>roundingMode</tt> does not
  624. * represent a valid rounding mode.
  625. * @see #ROUND_UP
  626. * @see #ROUND_DOWN
  627. * @see #ROUND_CEILING
  628. * @see #ROUND_FLOOR
  629. * @see #ROUND_HALF_UP
  630. * @see #ROUND_HALF_DOWN
  631. * @see #ROUND_HALF_EVEN
  632. * @see #ROUND_UNNECESSARY
  633. */
  634. public BigDecimal setScale(int scale, int roundingMode) {
  635. if (scale < 0)
  636. throw new ArithmeticException("Negative scale");
  637. if (roundingMode < ROUND_UP || roundingMode > ROUND_UNNECESSARY)
  638. throw new IllegalArgumentException("Invalid rounding mode");
  639. /* Handle the easy cases */
  640. if (scale == this.scale)
  641. return this;
  642. else if (scale > this.scale)
  643. return new BigDecimal(timesTenToThe(intVal, scale-this.scale),
  644. scale);
  645. else /* scale < this.scale */
  646. return divide(valueOf(1), scale, roundingMode);
  647. }
  648. /**
  649. * Returns a BigDecimal whose scale is the specified value, and whose
  650. * value is numerically equal to this BigDecimal's. Throws an
  651. * ArithmeticException if this is not possible. This call is typically
  652. * used to increase the scale, in which case it is guaranteed that there
  653. * exists a BigDecimal of the specified scale and the correct value. The
  654. * call can also be used to reduce the scale if the caller knows that the
  655. * BigDecimal has sufficiently many zeros at the end of its fractional
  656. * part (i.e., factors of ten in its integer value) to allow for the
  657. * rescaling without loss of precision.
  658. * <p>
  659. * This method returns the same result as the two argument version
  660. * of setScale, but saves the caller the trouble of specifying a
  661. * rounding mode in cases where it is irrelevant.
  662. * <p>
  663. * Note that since BigDecimal objects are immutable, calls of this
  664. * method do <i>not</i> result in the original object being
  665. * modified, contrary to the usual convention of having methods
  666. * named <code>set<i>X</i></code> mutate field
  667. * <code><i>X</i></code>. Instead, <code>setScale</code> returns
  668. * an object with the proper scale; the returned object may or may
  669. * not be newly allocated.
  670. *
  671. * @param scale scale of the BigDecimal value to be returned.
  672. * @return a BigDecimal whose scale is the specified value, and whose
  673. * unscaled value is determined by multiplying or dividing this
  674. * BigDecimal's unscaled value by the appropriate power of ten to
  675. * maintain its overall value.
  676. * @throws ArithmeticException <tt>scale</tt> is negative, or
  677. * the specified scaling operation would require rounding.
  678. * @see #setScale(int, int)
  679. */
  680. public BigDecimal setScale(int scale) {
  681. return setScale(scale, ROUND_UNNECESSARY);
  682. }
  683. // Decimal Point Motion Operations
  684. /**
  685. * Returns a BigDecimal which is equivalent to this one with the decimal
  686. * point moved n places to the left. If n is non-negative, the call merely
  687. * adds n to the scale. If n is negative, the call is equivalent to
  688. * movePointRight(-n). (The BigDecimal returned by this call has value
  689. * <tt>(this * 10<sup>-n</sup>)</tt> and scale
  690. * <tt>max(this.scale()+n, 0)</tt>.)
  691. *
  692. * @param n number of places to move the decimal point to the left.
  693. * @return a BigDecimal which is equivalent to this one with the decimal
  694. * point moved <tt>n</tt> places to the left.
  695. */
  696. public BigDecimal movePointLeft(int n){
  697. return (n>=0 ? new BigDecimal(intVal, scale+n) : movePointRight(-n));
  698. }
  699. /**
  700. * Moves the decimal point the specified number of places to the right.
  701. * If this BigDecimal's scale is >= <tt>n</tt>, the call merely
  702. * subtracts <tt>n</tt> from the scale; otherwise, it sets the scale to
  703. * zero, and multiplies the integer value by
  704. * <tt>10<sup>(n - this.scale)</sup></tt>. If <tt>n</tt>
  705. * is negative, the call is equivalent to <tt>movePointLeft(-n)</tt>. (The
  706. * BigDecimal returned by this call has value
  707. * <tt>(this * 10<sup>n</sup>)</tt> and scale
  708. * <tt>max(this.scale()-n, 0)</tt>.)
  709. *
  710. * @param n number of places to move the decimal point to the right.
  711. * @return a BigDecimal which is equivalent to this one with the decimal
  712. * point moved <tt>n</tt> places to the right.
  713. */
  714. public BigDecimal movePointRight(int n){
  715. return (scale >= n ? new BigDecimal(intVal, scale-n)
  716. : new BigDecimal(timesTenToThe(intVal, n-scale),0));
  717. }
  718. // Comparison Operations
  719. /**
  720. * Compares this BigDecimal with the specified BigDecimal. Two
  721. * BigDecimals that are equal in value but have a different scale (like
  722. * 2.0 and 2.00) are considered equal by this method. This method is
  723. * provided in preference to individual methods for each of the six
  724. * boolean comparison operators (<, ==, >, >=, !=, <=). The
  725. * suggested idiom for performing these comparisons is:
  726. * <tt>(x.compareTo(y)</tt> <<i>op</i>> <tt>0)</tt>,
  727. * where <<i>op</i>> is one of the six comparison operators.
  728. *
  729. * @param val BigDecimal to which this BigDecimal is to be compared.
  730. * @return -1, 0 or 1 as this BigDecimal is numerically less than, equal
  731. * to, or greater than <tt>val</tt>.
  732. */
  733. public int compareTo(BigDecimal val){
  734. /* Optimization: would run fine without the next three lines */
  735. int sigDiff = signum() - val.signum();
  736. if (sigDiff != 0)
  737. return (sigDiff > 0 ? 1 : -1);
  738. /* If signs match, scale and compare intVals */
  739. BigDecimal arg[] = new BigDecimal[2];
  740. arg[0] = this; arg[1] = val;
  741. matchScale(arg);
  742. return arg[0].intVal.compareTo(arg[1].intVal);
  743. }
  744. /**
  745. * Compares this BigDecimal with the specified Object. If the Object is a
  746. * BigDecimal, this method behaves like {@link #compareTo compareTo}.
  747. * Otherwise, it throws a <tt>ClassCastException</tt> (as BigDecimals are
  748. * comparable only to other BigDecimals).
  749. *
  750. * @param o Object to which this BigDecimal is to be compared.
  751. * @return a negative number, zero, or a positive number as this
  752. * BigDecimal is numerically less than, equal to, or greater
  753. * than <tt>o</tt>, which must be a BigDecimal.
  754. * @throws ClassCastException <tt>o</tt> is not a BigDecimal.
  755. * @see #compareTo(java.math.BigDecimal)
  756. * @see Comparable
  757. * @since 1.2
  758. */
  759. public int compareTo(Object o) {
  760. return compareTo((BigDecimal)o);
  761. }
  762. /**
  763. * Compares this BigDecimal with the specified Object for
  764. * equality. Unlike {@link #compareTo compareTo}, this method
  765. * considers two BigDecimals equal only if they are equal in value
  766. * and scale (thus 2.0 is not equal to 2.00 when compared by this
  767. * method).
  768. *
  769. * @param x Object to which this BigDecimal is to be compared.
  770. * @return <tt>true</tt> if and only if the specified Object is a
  771. * BigDecimal whose value and scale are equal to this BigDecimal's.
  772. * @see #compareTo(java.math.BigDecimal)
  773. */
  774. public boolean equals(Object x){
  775. if (!(x instanceof BigDecimal))
  776. return false;
  777. BigDecimal xDec = (BigDecimal) x;
  778. return scale == xDec.scale && intVal.equals(xDec.intVal);
  779. }
  780. /**
  781. * Returns the minimum of this BigDecimal and <tt>val</tt>.
  782. *
  783. * @param val value with which the minimum is to be computed.
  784. * @return the BigDecimal whose value is the lesser of this BigDecimal and
  785. * <tt>val</tt>. If they are equal, as defined by the
  786. * {@link #compareTo compareTo} method, either may be returned.
  787. * @see #compareTo(java.math.BigDecimal)
  788. */
  789. public BigDecimal min(BigDecimal val){
  790. return (compareTo(val)<0 ? this : val);
  791. }
  792. /**
  793. * Returns the maximum of this BigDecimal and <tt>val</tt>.
  794. *
  795. * @param val value with which the maximum is to be computed.
  796. * @return the BigDecimal whose value is the greater of this BigDecimal
  797. * and <tt>val</tt>. If they are equal, as defined by the
  798. * {@link #compareTo compareTo} method, either may be returned.
  799. * @see #compareTo(java.math.BigDecimal)
  800. */
  801. public BigDecimal max(BigDecimal val){
  802. return (compareTo(val)>0 ? this : val);
  803. }
  804. // Hash Function
  805. /**
  806. * Returns the hash code for this BigDecimal. Note that two BigDecimals
  807. * that are numerically equal but differ in scale (like 2.0 and 2.00)
  808. * will generally <i>not</i> have the same hash code.
  809. *
  810. * @return hash code for this BigDecimal.
  811. */
  812. public int hashCode() {
  813. return 31*intVal.hashCode() + scale;
  814. }
  815. //
  816. // add one to the least significant digit.
  817. // in the unlikely event there is a carry out,
  818. // deal with it.
  819. //
  820. private String
  821. roundup(String val){
  822. int i;
  823. char[] digits = val.toCharArray();
  824. int nDigits = digits.length;
  825. int q = digits[ i = (nDigits-1)];
  826. if ( q == '9' ){
  827. while ( q == '9' && i > 0 ){
  828. digits[i] = '0';
  829. q = digits[--i];
  830. }
  831. if ( q == '9' ){
  832. // carryout! High-order 1, rest 0s, larger exp.
  833. digits[0] = '0';
  834. return "1" + String.valueOf(digits);
  835. }
  836. // else fall through.
  837. }
  838. digits[i] = (char)(q+1);
  839. return String.valueOf(digits);
  840. }
  841. // Format Converters
  842. /**
  843. * Returns the string representation of this BigDecimal. The digit-to-
  844. * character mapping provided by {@link Character#forDigit} is used.
  845. * A leading minus sign is used to indicate sign, and the number of digits
  846. * to the right of the decimal point is used to indicate scale. (This
  847. * representation is compatible with the (String) constructor.)
  848. *
  849. * @return String representation of this BigDecimal.
  850. * @see Character#forDigit
  851. * @see #BigDecimal(java.lang.String)
  852. */
  853. public String toString(){
  854. if (scale == 0) /* No decimal point */
  855. return intVal.toString();
  856. return getValueString(signum(), intVal.abs().toString(), scale);
  857. }
  858. /**
  859. * Converts this BigDecimal to a BigInteger. This conversion is
  860. * analogous to a <a
  861. * href="http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363"><i>narrowing
  862. * primitive conversion</i></a> from <code>double</code> to
  863. * <code>long</code> as defined in the <a
  864. * href="http://java.sun.com/docs/books/jls/html/">Java Language
  865. * Specification</a>: any fractional part of this BigDecimal will
  866. * be discarded. Note that this conversion can lose information
  867. * about the precision of the BigDecimal value.
  868. *
  869. * @return this BigDecimal converted to a BigInteger.
  870. */
  871. public BigInteger toBigInteger() {
  872. return (scale==0 ? intVal
  873. : intVal.divide(BigInteger.valueOf(10).pow(scale)));
  874. }
  875. /**
  876. * Converts this BigDecimal to an <code>int</code>. This
  877. * conversion is analogous to a <a
  878. * href="http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363"><i>narrowing
  879. * primitive conversion</i></a> from <code>double</code> to
  880. * <code>short</code> as defined in the <a
  881. * href="http://java.sun.com/docs/books/jls/html/">Java Language
  882. * Specification</a>: any fractional part of this BigDecimal will
  883. * be discarded, and if the resulting "BigInteger" is
  884. * too big to fit in an <code>int</code>, only the low-order 32
  885. * bits are returned. Note that this conversion can lose
  886. * information about the overall magnitude and precision of the
  887. * BigDecimal value as well as return a result with the opposite
  888. * sign.
  889. *
  890. * @return this BigDecimal converted to an <code>int</code>.
  891. */
  892. public int intValue(){
  893. return toBigInteger().intValue();
  894. }
  895. /**
  896. * Converts this BigDecimal to a <code>long</code>. This
  897. * conversion is analogous to a <a
  898. * href="http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363"><i>narrowing
  899. * primitive conversion</i></a> from <code>double</code> to
  900. * <code>short</code> as defined in the <a
  901. * href="http://java.sun.com/docs/books/jls/html/">Java Language
  902. * Specification</a>: any fractional part of this BigDecimal will
  903. * be discarded, and if the resulting "BigInteger" is
  904. * too big to fit in a <code>long</code>, only the low-order 64
  905. * bits are returned. Note that this conversion can lose
  906. * information about the overall magnitude and precision of the
  907. * BigDecimal value as well as return a result with the opposite
  908. * sign.
  909. *
  910. * @return this BigDecimal converted to an <code>long</code>.
  911. */
  912. public long longValue(){
  913. return toBigInteger().longValue();
  914. }
  915. /**
  916. * Converts this BigDecimal to a <code>float</code>. This
  917. * conversion is similar to the <a
  918. * href="http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363"><i>narrowing
  919. * primitive conversion</i></a> from <code>double</code> to
  920. * <code>float</code> defined in the <a
  921. * href="http://java.sun.com/docs/books/jls/html/">Java Language
  922. * Specification</a>: if this BigDecimal has too great a magnitude
  923. * to represent as a <code>float</code>, it will be converted to
  924. * {@link Float#NEGATIVE_INFINITY} or {@link
  925. * Float#POSITIVE_INFINITY} as appropriate. Note that even when
  926. * the return value is finite, this conversion can lose
  927. * information about the precision of the BigDecimal value.
  928. *
  929. * @return this BigDecimal converted to a <code>float</code>.
  930. */
  931. public float floatValue(){
  932. /* Somewhat inefficient, but guaranteed to work. */
  933. return Float.valueOf(this.toString()).floatValue();
  934. }
  935. /**
  936. * Converts this BigDecimal to a <code>double</code>. This
  937. * conversion is similar to the <a
  938. * href="http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363"><i>narrowing
  939. * primitive conversion</i></a> from <code>double</code> to
  940. * <code>float</code> as defined in the <a
  941. * href="http://java.sun.com/docs/books/jls/html/">Java Language
  942. * Specification</a>: if this BigDecimal has too great a magnitude
  943. * represent as a <code>double</code>, it will be converted to
  944. * {@link Double#NEGATIVE_INFINITY} or {@link
  945. * Double#POSITIVE_INFINITY} as appropriate. Note that even when
  946. * the return value is finite, this conversion can lose
  947. * information about the precision of the BigDecimal value.
  948. *
  949. * @return this BigDecimal converted to a <code>double</code>.
  950. */
  951. public double doubleValue(){
  952. /* Somewhat inefficient, but guaranteed to work. */
  953. return Double.valueOf(this.toString()).doubleValue();
  954. }
  955. // Private "Helper" Methods
  956. /* Returns a digit.digit string */
  957. private String getValueString(int signum, String intString, int scale) {
  958. /* Insert decimal point */
  959. StringBuffer buf;
  960. int insertionPoint = intString.length() - scale;
  961. if (insertionPoint == 0) { /* Point goes right before intVal */
  962. return (signum<0 ? "-0." : "0.") + intString;
  963. } else if (insertionPoint > 0) { /* Point goes inside intVal */
  964. buf = new StringBuffer(intString);
  965. buf.insert(insertionPoint, '.');
  966. if (signum < 0)
  967. buf.insert(0, '-');
  968. } else { /* We must insert zeros between point and intVal */
  969. buf = new StringBuffer(3-insertionPoint + intString.length());
  970. buf.append(signum<0 ? "-0." : "0.");
  971. for (int i=0; i<-insertionPoint; i++)
  972. buf.append('0');
  973. buf.append(intString);
  974. }
  975. return buf.toString();
  976. }
  977. /* Returns (a * 10^b) */
  978. private static BigInteger timesTenToThe(BigInteger a, int b) {
  979. return a.multiply(BigInteger.valueOf(10).pow(b));
  980. }
  981. /*
  982. * If the scales of val[0] and val[1] differ, rescale (non-destructively)
  983. * the lower-scaled BigDecimal so they match.
  984. */
  985. private static void matchScale(BigDecimal[] val) {
  986. if (val[0].scale < val[1].scale)
  987. val[0] = val[0].setScale(val[1].scale);
  988. else if (val[1].scale < val[0].scale)
  989. val[1] = val[1].setScale(val[0].scale);
  990. }
  991. /**
  992. * Reconstitute the <tt>BigDecimal</tt> instance from a stream (that is,
  993. * deserialize it).
  994. */
  995. private synchronized void readObject(java.io.ObjectInputStream s)
  996. throws java.io.IOException, ClassNotFoundException {
  997. // Read in all fields
  998. s.defaultReadObject();
  999. // Validate scale factor
  1000. if (scale < 0)
  1001. throw new java.io.StreamCorruptedException(
  1002. "BigDecimal: Negative scale");
  1003. }
  1004. }