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