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