1. /*
  2. * @(#)BigDecimal.java 1.53 04/06/28
  3. *
  4. * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. /*
  8. * @(#)BigDecimal.java 1.x 01/xx/xx
  9. *
  10. * Copyright 1996-2001 Sun Microsystems, Inc. All Rights Reserved.
  11. * Portions Copyright IBM Corporation, 2001. All Rights Reserved.
  12. *
  13. * This software is the proprietary information of Sun Microsystems, Inc.
  14. * Use is subject to license terms.
  15. *
  16. */
  17. package java.math;
  18. /**
  19. * Immutable, arbitrary-precision signed decimal numbers. A
  20. * <tt>BigDecimal</tt> consists of an arbitrary precision integer
  21. * <i>unscaled value</i> and a 32-bit integer <i>scale</i>. If zero
  22. * or positive, the scale is the number of digits to the right of the
  23. * decimal point. If negative, the unscaled value of the number is
  24. * multiplied by ten to the power of the negation of the scale. The
  25. * value of the number represented by the <tt>BigDecimal</tt> is
  26. * therefore <tt>(unscaledValue × 10<sup>-scale</sup>)</tt>.
  27. *
  28. * <p>The <tt>BigDecimal</tt> class provides operations for
  29. * arithmetic, scale manipulation, rounding, comparison, hashing, and
  30. * format conversion. The {@link #toString} method provides a
  31. * canonical representation of a <tt>BigDecimal</tt>.
  32. *
  33. * <p>The <tt>BigDecimal</tt> class gives its user complete control
  34. * over rounding behavior. If no rounding mode is specified and the
  35. * exact result cannot be represented, an exception is thrown;
  36. * otherwise, calculations can be carried out to a chosen precision
  37. * and rounding mode by supplying an appropriate {@link MathContext}
  38. * object to the operation. In either case, eight <em>rounding
  39. * modes</em> are provided for the control of rounding. Using the
  40. * integer fields in this class (such as {@link #ROUND_HALF_UP}) to
  41. * represent rounding mode is largely obsolete; the enumeration values
  42. * of the <tt>RoundingMode</tt> <tt>enum</tt>, (such as {@link
  43. * RoundingMode#HALF_UP}) should be used instead.
  44. *
  45. * <p>When a <tt>MathContext</tt> object is supplied with a precision
  46. * setting of 0 (for example, {@link MathContext#UNLIMITED}),
  47. * arithmetic operations are exact, as are the arithmetic methods
  48. * which take no <tt>MathContext</tt> object. (This is the only
  49. * behavior that was supported in releases prior to 5.) As a
  50. * corollary of computing the exact result, the rounding mode setting
  51. * of a <tt>MathContext</tt> object with a precision setting of 0 is
  52. * not used and thus irrelevant. In the case of divide, the exact
  53. * quotient could have an infinitely long decimal expansion; for
  54. * example, 1 divided by 3. If the quotient has a nonterminating
  55. * decimal expansion and the operation is specified to return an exact
  56. * result, an <tt>ArithmeticException</tt> is thrown. Otherwise, the
  57. * exact result of the division is returned, as done for other
  58. * operations.
  59. *
  60. * <p>When the precision setting is not 0, the rules of
  61. * <tt>BigDecimal</tt> arithmetic are broadly compatible with selected
  62. * modes of operation of the arithmetic defined in ANSI X3.274-1996
  63. * and ANSI X3.274-1996/AM 1-2000 (section 7.4). Unlike those
  64. * standards, <tt>BigDecimal</tt> includes many rounding modes, which
  65. * were mandatory for division in <tt>BigDecimal</tt> releases prior
  66. * to 5. Any conflicts between these ANSI standards and the
  67. * <tt>BigDecimal</tt> specification are resolved in favor of
  68. * <tt>BigDecimal</tt>.
  69. *
  70. * <p>Since the same numerical value can have different
  71. * representations (with different scales), the rules of arithmetic
  72. * and rounding must specify both the numerical result and the scale
  73. * used in the result's representation.
  74. *
  75. *
  76. * <p>In general the rounding modes and precision setting determine
  77. * how operations return results with a limited number of digits when
  78. * the exact result has more digits (perhaps infinitely many in the
  79. * case of division) than the number of digits returned.
  80. *
  81. * First, the
  82. * total number of digits to return is specified by the
  83. * <tt>MathContext</tt>'s <tt>precision</tt> setting; this determines
  84. * the result's <i>precision</i>. The digit count starts from the
  85. * leftmost nonzero digit of the exact result. The rounding mode
  86. * determines how any discarded trailing digits affect the returned
  87. * result.
  88. *
  89. * <p>For all arithmetic operators , the operation is carried out as
  90. * though an exact intermediate result were first calculated and then
  91. * rounded to the number of digits specified by the precision setting
  92. * (if necessary), using the selected rounding mode. If the exact
  93. * result is not returned, some digit positions of the exact result
  94. * are discarded. When rounding increases the magnitude of the
  95. * returned result, it is possible for a new digit position to be
  96. * created by a carry propagating to a leading "9" digit.
  97. * For example, rounding the value 999.9 to three digits rounding up
  98. * would be numerically equal to one thousand, represented as
  99. * 100×10<sup>1</sup>. In such cases, the new "1" is
  100. * the leading digit position of the returned result.
  101. *
  102. * <p>Besides a logical exact result, each arithmetic operation has a
  103. * preferred scale for representing a result. The preferred
  104. * scale for each operation is listed in the table below.
  105. *
  106. * <table border>
  107. * <caption top><h3>Preferred Scales for Results of Arithmetic Operations
  108. * </h3></caption>
  109. * <tr><th>Operation</th><th>Preferred Scale of Result</th></tr>
  110. * <tr><td>Add</td><td>max(addend.scale(), augend.scale())</td>
  111. * <tr><td>Subtract</td><td>max(minuend.scale(), subtrahend.scale())</td>
  112. * <tr><td>Multiply</td><td>multiplier.scale() + multiplicand.scale()</td>
  113. * <tr><td>Divide</td><td>dividend.scale() - divisor.scale()</td>
  114. * </table>
  115. *
  116. * These scales are the ones used by the methods which return exact
  117. * arithmetic results; except that an exact divide may have to use a
  118. * larger scale since the exact result may have more digits. For
  119. * example, <tt>1/32</tt> is <tt>0.03125</tt>.
  120. *
  121. * <p>Before rounding, the scale of the logical exact intermediate
  122. * result is the preferred scale for that operation. If the exact
  123. * numerical result cannot be represented in <code>precision</code>
  124. * digits, rounding selects the set of digits to return and the scale
  125. * of the result is reduced from the scale of the intermediate result
  126. * to the least scale which can represent the <code>precision</code>
  127. * digits actually returned. If the exact result can be represented
  128. * with at most <code>precision</code> digits, the representation
  129. * of the result with the scale closest to the preferred scale is
  130. * returned. In particular, an exactly representable quotient may be
  131. * represented in fewer than <code>precision</code> digits by removing
  132. * trailing zeros and decreasing the scale. For example, rounding to
  133. * three digits using the {@linkplain RoundingMode#FLOOR floor}
  134. * rounding mode, <br>
  135. *
  136. * <code>19/100 = 0.19 // integer=19, scale=2</code> <br>
  137. *
  138. * but<br>
  139. *
  140. * <code>21/110 = 0.190 // integer=190, scale=3</code> <br>
  141. *
  142. * <p>Note that for add, subtract, and multiply, the reduction in
  143. * scale will equal the number of digit positions of the exact result
  144. * which are discarded. If the rounding causes a carry propagation to
  145. * create a new high-order digit position, an additional digit of the
  146. * result is discarded than when no new digit position is created.
  147. *
  148. * <p>Other methods may have slightly different rounding semantics.
  149. * For example, the result of the <tt>pow</tt> method using the
  150. * {@linkplain #pow(int, MathContext) specified algorithm} can
  151. * occasionally differ from the rounded mathematical result by more
  152. * than one unit in the last place, one <i>{@linkplain #ulp() ulp}</i>.
  153. *
  154. * <p>Two types of operations are provided for manipulating the scale
  155. * of a <tt>BigDecimal</tt>: scaling/rounding operations and decimal
  156. * point motion operations. Scaling/rounding operations ({@link
  157. * #setScale setScale} and {@link #round round}) return a
  158. * <tt>BigDecimal</tt> whose value is approximately (or exactly) equal
  159. * to that of the operand, but whose scale or precision is the
  160. * specified value; that is, they increase or decrease the precision
  161. * of the stored number with minimal effect on its value. Decimal
  162. * point motion operations ({@link #movePointLeft movePointLeft} and
  163. * {@link #movePointRight movePointRight}) return a
  164. * <tt>BigDecimal</tt> created from the operand by moving the decimal
  165. * point a specified distance in the specified direction.
  166. *
  167. * <p>For the sake of brevity and clarity, pseudo-code is used
  168. * throughout the descriptions of <tt>BigDecimal</tt> methods. The
  169. * pseudo-code expression <tt>(i + j)</tt> is shorthand for "a
  170. * <tt>BigDecimal</tt> whose value is that of the <tt>BigDecimal</tt>
  171. * <tt>i</tt> added to that of the <tt>BigDecimal</tt>
  172. * <tt>j</tt>." The pseudo-code expression <tt>(i == j)</tt> is
  173. * shorthand for "<tt>true</tt> if and only if the
  174. * <tt>BigDecimal</tt> <tt>i</tt> represents the same value as the
  175. * <tt>BigDecimal</tt> <tt>j</tt>." Other pseudo-code expressions
  176. * are interpreted similarly. Square brackets are used to represent
  177. * the particular <tt>BigInteger</tt> and scale pair defining a
  178. * <tt>BigDecimal</tt> value; for example [19, 2] is the
  179. * <tt>BigDecimal</tt> numerically equal to 0.19 having a scale of 2.
  180. *
  181. * <p>Note: care should be exercised if <tt>BigDecimal</tt> objects
  182. * are used as keys in a {@link java.util.SortedMap SortedMap} or
  183. * elements in a {@link java.util.SortedSet SortedSet} since
  184. * <tt>BigDecimal</tt>'s <i>natural ordering</i> is <i>inconsistent
  185. * with equals</i>. See {@link Comparable}, {@link
  186. * java.util.SortedMap} or {@link java.util.SortedSet} for more
  187. * information.
  188. *
  189. * <p>All methods and constructors for this class throw
  190. * <tt>NullPointerException</tt> when passed a <tt>null</tt> object
  191. * reference for any input parameter.
  192. *
  193. * @see BigInteger
  194. * @see MathContext
  195. * @see RoundingMode
  196. * @see java.util.SortedMap
  197. * @see java.util.SortedSet
  198. * @author Josh Bloch
  199. * @author Mike Cowlishaw
  200. * @author Joseph D. Darcy
  201. */
  202. public class BigDecimal extends Number implements Comparable<BigDecimal> {
  203. /**
  204. * The unscaled value of this BigDecimal, as returned by {@link
  205. * #unscaledValue}.
  206. *
  207. * @serial
  208. * @see #unscaledValue
  209. */
  210. private BigInteger intVal;
  211. /**
  212. * The scale of this BigDecimal, as returned by {@link #scale}.
  213. *
  214. * @serial
  215. * @see #scale
  216. */
  217. private int scale = 0; // Note: this may have any value, so
  218. // calculations must be done in longs
  219. /**
  220. * The number of decimal digits in this BigDecimal, or 0 if the
  221. * number of digits are not known (lookaside information). If
  222. * nonzero, the value is guaranteed correct. Use the precision()
  223. * method to obtain and set the value if it might be 0. This
  224. * field is mutable until set nonzero.
  225. *
  226. * @since 1.5
  227. */
  228. private volatile transient int precision = 0;
  229. /* Appease the serialization gods */
  230. private static final long serialVersionUID = 6108874887143696463L;
  231. // Constants
  232. /**
  233. * The value 0, with a scale of 0.
  234. *
  235. * @since 1.5
  236. */
  237. public static final BigDecimal ZERO =
  238. new BigDecimal(BigInteger.ZERO, 0);
  239. /**
  240. * The value 1, with a scale of 0.
  241. *
  242. * @since 1.5
  243. */
  244. public static final BigDecimal ONE =
  245. new BigDecimal(BigInteger.ONE, 0);
  246. /**
  247. * The value 10, with a scale of 0.
  248. *
  249. * @since 1.5
  250. */
  251. public static final BigDecimal TEN =
  252. new BigDecimal(BigInteger.TEN, 0);
  253. // Constructors
  254. /**
  255. * Translates a character array representation of a
  256. * <tt>BigDecimal</tt> into a <tt>BigDecimal</tt>, accepting the
  257. * same sequence of characters as the {@link #BigDecimal(String)}
  258. * constructor, while allowing a sub-array to be specified.
  259. *
  260. * <p>Note that if the sequence of characters is already available
  261. * within a character array, using this constructor is faster than
  262. * converting the <tt>char</tt> array to string and using the
  263. * <tt>BigDecimal(String)</tt> constructor .
  264. *
  265. * @param in <tt>char</tt> array that is the source of characters.
  266. * @param offset first character in the array to inspect.
  267. * @param len number of characters to consider.
  268. * @throws NumberFormatException if <tt>in</tt> is not a valid
  269. * representation of a <tt>BigDecimal</tt> or the defined subarray
  270. * is not wholly within <tt>in</tt>.
  271. * @since 1.5
  272. */
  273. public BigDecimal(char[] in, int offset, int len) {
  274. // This is the primary string to BigDecimal constructor; all
  275. // incoming strings end up here; it uses explicit (inline)
  276. // parsing for speed and generates at most one intermediate
  277. // (temporary) object (a char[] array).
  278. // use array bounds checking to handle too-long, len == 0,
  279. // bad offset, etc.
  280. try {
  281. // handle the sign
  282. boolean isneg = false; // assume positive
  283. if (in[offset] == '-') {
  284. isneg = true; // leading minus means negative
  285. offset++;
  286. len--;
  287. } else if (in[offset] == '+') { // leading + allowed
  288. offset++;
  289. len--;
  290. }
  291. // should now be at numeric part of the significand
  292. int dotoff = -1; // '.' offset, -1 if none
  293. int cfirst = offset; // record start of integer
  294. long exp = 0; // exponent
  295. if (len > in.length) // protect against huge length
  296. throw new NumberFormatException();
  297. char coeff[] = new char[len]; // integer significand array
  298. char c; // work
  299. for (; len > 0; offset++, len--) {
  300. c = in[offset];
  301. if ((c >= '0' && c <= '9') || Character.isDigit(c)) {
  302. // have digit
  303. coeff[precision] = c;
  304. precision++; // count of digits
  305. continue;
  306. }
  307. if (c == '.') {
  308. // have dot
  309. if (dotoff >= 0) // two dots
  310. throw new NumberFormatException();
  311. dotoff = offset;
  312. continue;
  313. }
  314. // exponent expected
  315. if ((c != 'e') && (c != 'E'))
  316. throw new NumberFormatException();
  317. offset++;
  318. c = in[offset];
  319. len--;
  320. boolean negexp = false;
  321. // optional sign
  322. if (c == '-' || c == '+') {
  323. negexp = (c == '-');
  324. offset++;
  325. c = in[offset];
  326. len--;
  327. }
  328. if (len <= 0 || len > 10) // no digits, or too long
  329. throw new NumberFormatException();
  330. // c now holds first digit of exponent
  331. for (;; len--) {
  332. int v;
  333. if (c >= '0' && c <= '9') {
  334. v = c - '0';
  335. } else {
  336. v = Character.digit(c, 10);
  337. if (v < 0) // not a digit
  338. throw new NumberFormatException();
  339. }
  340. exp = exp * 10 + v;
  341. if (len == 1)
  342. break; // that was final character
  343. offset++;
  344. c = in[offset];
  345. }
  346. if (negexp) // apply sign
  347. exp = -exp;
  348. // Next test is required for backwards compatibility
  349. if ((int)exp != exp) // overflow
  350. throw new NumberFormatException();
  351. break; // [saves a test]
  352. }
  353. // here when no characters left
  354. if (precision == 0) // no digits found
  355. throw new NumberFormatException();
  356. if (dotoff >= 0) { // had dot; set scale
  357. scale = precision - (dotoff - cfirst);
  358. // [cannot overflow]
  359. }
  360. if (exp != 0) { // had significant exponent
  361. try {
  362. scale = checkScale(-exp + scale); // adjust
  363. } catch (ArithmeticException e) {
  364. throw new NumberFormatException("Scale out of range.");
  365. }
  366. }
  367. // Remove leading zeros from precision (digits count)
  368. int first = 0;
  369. for (; coeff[first] == '0' && precision > 1; first++)
  370. precision--;
  371. // Set the significand ..
  372. // Copy significand to exact-sized array, with sign if
  373. // negative
  374. // Later use: BigInteger(coeff, first, precision) for
  375. // both cases, by allowing an extra char at the front of
  376. // coeff.
  377. char quick[];
  378. if (!isneg) {
  379. quick = new char[precision];
  380. System.arraycopy(coeff, first, quick, 0, precision);
  381. } else {
  382. quick = new char[precision+1];
  383. quick[0] = '-';
  384. System.arraycopy(coeff, first, quick, 1, precision);
  385. }
  386. intVal = new BigInteger(quick);
  387. // System.out.println(" new: " +intVal+" ["+scale+"] "+precision);
  388. } catch (ArrayIndexOutOfBoundsException e) {
  389. throw new NumberFormatException();
  390. } catch (NegativeArraySizeException e) {
  391. throw new NumberFormatException();
  392. }
  393. }
  394. /**
  395. * Translates a character array representation of a
  396. * <tt>BigDecimal</tt> into a <tt>BigDecimal</tt>, accepting the
  397. * same sequence of characters as the {@link #BigDecimal(String)}
  398. * constructor, while allowing a sub-array to be specified and
  399. * with rounding according to the context settings.
  400. *
  401. * <p>Note that if the sequence of characters is already available
  402. * within a character array, using this constructor is faster than
  403. * converting the <tt>char</tt> array to string and using the
  404. * <tt>BigDecimal(String)</tt> constructor .
  405. *
  406. * @param in <tt>char</tt> array that is the source of characters.
  407. * @param offset first character in the array to inspect.
  408. * @param len number of characters to consider..
  409. * @param mc the context to use.
  410. * @throws ArithmeticException if the result is inexact but the
  411. * rounding mode is <tt>UNNECESSARY</tt>.
  412. * @throws NumberFormatException if <tt>in</tt> is not a valid
  413. * representation of a <tt>BigDecimal</tt> or the defined subarray
  414. * is not wholly within <tt>in</tt>.
  415. * @since 1.5
  416. */
  417. public BigDecimal(char[] in, int offset, int len, MathContext mc) {
  418. this(in, offset, len);
  419. if (mc.precision > 0)
  420. roundThis(mc);
  421. }
  422. /**
  423. * Translates a character array representation of a
  424. * <tt>BigDecimal</tt> into a <tt>BigDecimal</tt>, accepting the
  425. * same sequence of characters as the {@link #BigDecimal(String)}
  426. * constructor.
  427. *
  428. * <p>Note that if the sequence of characters is already available
  429. * as a character array, using this constructor is faster than
  430. * converting the <tt>char</tt> array to string and using the
  431. * <tt>BigDecimal(String)</tt> constructor .
  432. *
  433. * @param in <tt>char</tt> array that is the source of characters.
  434. * @throws NumberFormatException if <tt>in</tt> is not a valid
  435. * representation of a <tt>BigDecimal</tt>.
  436. * @since 1.5
  437. */
  438. public BigDecimal(char[] in) {
  439. this(in, 0, in.length);
  440. }
  441. /**
  442. * Translates a character array representation of a
  443. * <tt>BigDecimal</tt> into a <tt>BigDecimal</tt>, accepting the
  444. * same sequence of characters as the {@link #BigDecimal(String)}
  445. * constructor and with rounding according to the context
  446. * settings.
  447. *
  448. * <p>Note that if the sequence of characters is already available
  449. * as a character array, using this constructor is faster than
  450. * converting the <tt>char</tt> array to string and using the
  451. * <tt>BigDecimal(String)</tt> constructor .
  452. *
  453. * @param in <tt>char</tt> array that is the source of characters.
  454. * @param mc the context to use.
  455. * @throws ArithmeticException if the result is inexact but the
  456. * rounding mode is <tt>UNNECESSARY</tt>.
  457. * @throws NumberFormatException if <tt>in</tt> is not a valid
  458. * representation of a <tt>BigDecimal</tt>.
  459. * @since 1.5
  460. */
  461. public BigDecimal(char[] in, MathContext mc) {
  462. this(in, 0, in.length, mc);
  463. }
  464. /**
  465. * Translates the string representation of a <tt>BigDecimal</tt>
  466. * into a <tt>BigDecimal</tt>. The string representation consists
  467. * of an optional sign, <tt>'+'</tt> (<tt>'\u002B'</tt>) or
  468. * <tt>'-'</tt> (<tt>'\u002D'</tt>), followed by a sequence of
  469. * zero or more decimal digits ("the integer"), optionally
  470. * followed by a fraction, optionally followed by an exponent.
  471. *
  472. * <p>The fraction consists of a decimal point followed by zero
  473. * or more decimal digits. The string must contain at least one
  474. * digit in either the integer or the fraction. The number formed
  475. * by the sign, the integer and the fraction is referred to as the
  476. * <i>significand</i>.
  477. *
  478. * <p>The exponent consists of the character <tt>'e'</tt>
  479. * (<tt>'\u0075'</tt>) or <tt>'E'</tt> (<tt>'\u0045'</tt>)
  480. * followed by one or more decimal digits. The value of the
  481. * exponent must lie between -{@link Integer#MAX_VALUE} ({@link
  482. * Integer#MIN_VALUE}+1) and {@link Integer#MAX_VALUE}, inclusive.
  483. *
  484. * <p>More formally, the strings this constructor accepts are
  485. * described by the following grammar:
  486. * <blockquote>
  487. * <dl>
  488. * <dt><i>BigDecimalString:</i>
  489. * <dd><i>Sign<sub>opt</sub> Significand Exponent<sub>opt</sub></i>
  490. * <p>
  491. * <dt><i>Sign:</i>
  492. * <dd><tt>+</tt>
  493. * <dd><tt>-</tt>
  494. * <p>
  495. * <dt><i>Significand:</i>
  496. * <dd><i>IntegerPart</i> <tt>.</tt> <i>FractionPart<sub>opt</sub></i>
  497. * <dd><tt>.</tt> <i>FractionPart</i>
  498. * <dd><i>IntegerPart</i>
  499. * <p>
  500. * <dt><i>IntegerPart:
  501. * <dd>Digits</i>
  502. * <p>
  503. * <dt><i>FractionPart:
  504. * <dd>Digits</i>
  505. * <p>
  506. * <dt><i>Exponent:
  507. * <dd>ExponentIndicator SignedInteger</i>
  508. * <p>
  509. * <dt><i>ExponentIndicator:</i>
  510. * <dd><tt>e</tt>
  511. * <dd><tt>E</tt>
  512. * <p>
  513. * <dt><i>SignedInteger:
  514. * <dd>Sign<sub>opt</sub> Digits</i>
  515. * <p>
  516. * <dt><i>Digits:
  517. * <dd>Digit
  518. * <dd>Digits Digit</i>
  519. * <p>
  520. * <dt><i>Digit:</i>
  521. * <dd>any character for which {@link Character#isDigit}
  522. * returns <tt>true</tt>, including 0, 1, 2 ...
  523. * </dl>
  524. * </blockquote>
  525. *
  526. * <p>The scale of the returned <tt>BigDecimal</tt> will be the
  527. * number of digits in the fraction, or zero if the string
  528. * contains no decimal point, subject to adjustment for any
  529. * exponent; if the string contains an exponent, the exponent is
  530. * subtracted from the scale. The value of the resulting scale
  531. * must lie between <tt>Integer.MIN_VALUE</tt> and
  532. * <tt>Integer.MAX_VALUE</tt>, inclusive.
  533. *
  534. * <p>The character-to-digit mapping is provided by {@link
  535. * java.lang.Character#digit} set to convert to radix 10. The
  536. * String may not contain any extraneous characters (whitespace,
  537. * for example).
  538. *
  539. * <p><b>Examples:</b><br>
  540. * The value of the returned <tt>BigDecimal</tt> is equal to
  541. * <i>significand</i> × 10<sup> <i>exponent</i></sup>.
  542. * For each string on the left, the resulting representation
  543. * [<tt>BigInteger</tt>, <tt>scale</tt>] is shown on the right.
  544. * <pre>
  545. * "0" [0,0]
  546. * "0.00" [0,2]
  547. * "123" [123,0]
  548. * "-123" [-123,0]
  549. * "1.23E3" [123,-1]
  550. * "1.23E+3" [123,-1]
  551. * "12.3E+7" [123,-6]
  552. * "12.0" [120,1]
  553. * "12.3" [123,1]
  554. * "0.00123" [123,5]
  555. * "-1.23E-12" [-123,14]
  556. * "1234.5E-4" [12345,5]
  557. * "0E+7" [0,-7]
  558. * "-0" [0,0]
  559. * </pre>
  560. *
  561. * <p>Note: For values other than <tt>float</tt> and
  562. * <tt>double</tt> NaN and ±Infinity, this constructor is
  563. * compatible with the values returned by {@link Float#toString}
  564. * and {@link Double#toString}. This is generally the preferred
  565. * way to convert a <tt>float</tt> or <tt>double</tt> into a
  566. * BigDecimal, as it doesn't suffer from the unpredictability of
  567. * the {@link #BigDecimal(double)} constructor.
  568. *
  569. * @param val String representation of <tt>BigDecimal</tt>.
  570. *
  571. * @throws NumberFormatException if <tt>val</tt> is not a valid
  572. * representation of a <tt>BigDecimal</tt>.
  573. */
  574. public BigDecimal(String val) {
  575. this(val.toCharArray(), 0, val.length());
  576. }
  577. /**
  578. * Translates the string representation of a <tt>BigDecimal</tt>
  579. * into a <tt>BigDecimal</tt>, accepting the same strings as the
  580. * {@link #BigDecimal(String)} constructor, with rounding
  581. * according to the context settings.
  582. *
  583. * @param val string representation of a <tt>BigDecimal</tt>.
  584. * @param mc the context to use.
  585. * @throws ArithmeticException if the result is inexact but the
  586. * rounding mode is <tt>UNNECESSARY</tt>.
  587. * @throws NumberFormatException if <tt>val</tt> is not a valid
  588. * representation of a BigDecimal.
  589. * @since 1.5
  590. */
  591. public BigDecimal(String val, MathContext mc) {
  592. this(val.toCharArray(), 0, val.length());
  593. if (mc.precision > 0)
  594. roundThis(mc);
  595. }
  596. /**
  597. * Translates a <tt>double</tt> into a <tt>BigDecimal</tt> which
  598. * is the exact decimal representation of the <tt>double</tt>'s
  599. * binary floating-point value. The scale of the returned
  600. * <tt>BigDecimal</tt> is the smallest value such that
  601. * <tt>(10<sup>scale</sup> × val)</tt> is an integer.
  602. * <p>
  603. * <b>Notes:</b>
  604. * <ol>
  605. * <li>
  606. * The results of this constructor can be somewhat unpredictable.
  607. * One might assume that writing <tt>new BigDecimal(0.1)</tt> in
  608. * Java creates a <tt>BigDecimal</tt> which is exactly equal to
  609. * 0.1 (an unscaled value of 1, with a scale of 1), but it is
  610. * actually equal to
  611. * 0.1000000000000000055511151231257827021181583404541015625.
  612. * This is because 0.1 cannot be represented exactly as a
  613. * <tt>double</tt> (or, for that matter, as a binary fraction of
  614. * any finite length). Thus, the value that is being passed
  615. * <i>in</i> to the constructor is not exactly equal to 0.1,
  616. * appearances notwithstanding.
  617. *
  618. * <li>
  619. * The <tt>String</tt> constructor, on the other hand, is
  620. * perfectly predictable: writing <tt>new BigDecimal("0.1")</tt>
  621. * creates a <tt>BigDecimal</tt> which is <i>exactly</i> equal to
  622. * 0.1, as one would expect. Therefore, it is generally
  623. * recommended that the {@linkplain #BigDecimal(String)
  624. * <tt>String</tt> constructor} be used in preference to this one.
  625. *
  626. * <li>
  627. * When a <tt>double</tt> must be used as a source for a
  628. * <tt>BigDecimal</tt>, note that this constructor provides an
  629. * exact conversion; it does not give the same result as
  630. * converting the <tt>double</tt> to a <tt>String</tt> using the
  631. * {@link Double#toString(double)} method and then using the
  632. * {@link #BigDecimal(String)} constructor. To get that result,
  633. * use the <tt>static</tt> {@link #valueOf(double)} method.
  634. * </ol>
  635. *
  636. * @param val <tt>double</tt> value to be converted to
  637. * <tt>BigDecimal</tt>.
  638. * @throws NumberFormatException if <tt>val</tt> is infinite or NaN.
  639. */
  640. public BigDecimal(double val) {
  641. if (Double.isInfinite(val) || Double.isNaN(val))
  642. throw new NumberFormatException("Infinite or NaN");
  643. // Translate the double into sign, exponent and mantissa, according
  644. // to the formulae in JLS, Section 20.10.22.
  645. long valBits = Double.doubleToLongBits(val);
  646. int sign = ((valBits >> 63)==0 ? 1 : -1);
  647. int exponent = (int) ((valBits >> 52) & 0x7ffL);
  648. long mantissa = (exponent==0 ? (valBits & ((1L<<52) - 1)) << 1
  649. : (valBits & ((1L<<52) - 1)) | (1L<<52));
  650. exponent -= 1075;
  651. /* At this point, val == sign * mantissa * 2**exponent */
  652. /*
  653. * Special case zero to supress nonterminating normalization
  654. * and bogus scale calculation.
  655. */
  656. if (mantissa == 0) {
  657. intVal = BigInteger.ZERO;
  658. precision = 1;
  659. return;
  660. }
  661. /* Normalize */
  662. while((mantissa & 1) == 0) { /* i.e., Mantissa is even */
  663. mantissa >>= 1;
  664. exponent++;
  665. }
  666. /* Calculate intVal and scale */
  667. intVal = BigInteger.valueOf(sign*mantissa);
  668. if (exponent < 0) {
  669. intVal = intVal.multiply(BigInteger.valueOf(5).pow(-exponent));
  670. scale = -exponent;
  671. } else if (exponent > 0) {
  672. intVal = intVal.multiply(BigInteger.valueOf(2).pow(exponent));
  673. }
  674. }
  675. /**
  676. * Translates a <tt>double</tt> into a <tt>BigDecimal</tt>, with
  677. * rounding according to the context settings. The scale of the
  678. * <tt>BigDecimal</tt> is the smallest value such that
  679. * <tt>(10<sup>scale</sup> × val)</tt> is an integer.
  680. *
  681. * <p>The results of this constructor can be somewhat unpredictable
  682. * and its use is generally not recommended; see the notes under
  683. * the {@link #BigDecimal(double)} constructor.
  684. *
  685. * @param val <tt>double</tt> value to be converted to
  686. * <tt>BigDecimal</tt>.
  687. * @param mc the context to use.
  688. * @throws ArithmeticException if the result is inexact but the
  689. * RoundingMode is UNNECESSARY.
  690. * @throws NumberFormatException if <tt>val</tt> is infinite or NaN.
  691. * @since 1.5
  692. */
  693. public BigDecimal(double val, MathContext mc) {
  694. this(val);
  695. if (mc.precision > 0)
  696. roundThis(mc);
  697. }
  698. /**
  699. * Translates a <tt>BigInteger</tt> into a <tt>BigDecimal</tt>.
  700. * The scale of the <tt>BigDecimal</tt> is zero.
  701. *
  702. * @param val <tt>BigInteger</tt> value to be converted to
  703. * <tt>BigDecimal</tt>.
  704. */
  705. public BigDecimal(BigInteger val) {
  706. intVal = val;
  707. }
  708. /**
  709. * Translates a <tt>BigInteger</tt> into a <tt>BigDecimal</tt>
  710. * rounding according to the context settings. The scale of the
  711. * <tt>BigDecimal</tt> is zero.
  712. *
  713. * @param val <tt>BigInteger</tt> value to be converted to
  714. * <tt>BigDecimal</tt>.
  715. * @param mc the context to use.
  716. * @throws ArithmeticException if the result is inexact but the
  717. * rounding mode is <tt>UNNECESSARY</tt>.
  718. * @since 1.5
  719. */
  720. public BigDecimal(BigInteger val, MathContext mc) {
  721. intVal = val;
  722. if (mc.precision > 0)
  723. roundThis(mc);
  724. }
  725. /**
  726. * Translates a <tt>BigInteger</tt> unscaled value and an
  727. * <tt>int</tt> scale into a <tt>BigDecimal</tt>. The value of
  728. * the <tt>BigDecimal</tt> is
  729. * <tt>(unscaledVal × 10<sup>-scale</sup>)</tt>.
  730. *
  731. * @param unscaledVal unscaled value of the <tt>BigDecimal</tt>.
  732. * @param scale scale of the <tt>BigDecimal</tt>.
  733. */
  734. public BigDecimal(BigInteger unscaledVal, int scale) {
  735. // Negative scales are now allowed
  736. intVal = unscaledVal;
  737. this.scale = scale;
  738. }
  739. /**
  740. * Translates a <tt>BigInteger</tt> unscaled value and an
  741. * <tt>int</tt> scale into a <tt>BigDecimal</tt>, with rounding
  742. * according to the context settings. The value of the
  743. * <tt>BigDecimal</tt> is <tt>(unscaledVal ×
  744. * 10<sup>-scale</sup>)</tt>, rounded according to the
  745. * <tt>precision</tt> and rounding mode settings.
  746. *
  747. * @param unscaledVal unscaled value of the <tt>BigDecimal</tt>.
  748. * @param scale scale of the <tt>BigDecimal</tt>.
  749. * @param mc the context to use.
  750. * @throws ArithmeticException if the result is inexact but the
  751. * rounding mode is <tt>UNNECESSARY</tt>.
  752. * @since 1.5
  753. */
  754. public BigDecimal(BigInteger unscaledVal, int scale, MathContext mc) {
  755. intVal = unscaledVal;
  756. this.scale = scale;
  757. if (mc.precision > 0)
  758. roundThis(mc);
  759. }
  760. /**
  761. * Translates an <tt>int</tt> into a <tt>BigDecimal</tt>. The
  762. * scale of the <tt>BigDecimal</tt> is zero.
  763. *
  764. * @param val <tt>int</tt> value to be converted to
  765. * <tt>BigDecimal</tt>.
  766. * @since 1.5
  767. */
  768. public BigDecimal(int val) {
  769. intVal = BigInteger.valueOf(val);
  770. }
  771. /**
  772. * Translates an <tt>int</tt> into a <tt>BigDecimal</tt>, with
  773. * rounding according to the context settings. The scale of the
  774. * <tt>BigDecimal</tt>, before any rounding, is zero.
  775. *
  776. * @param val <tt>int</tt> value to be converted to <tt>BigDecimal</tt>.
  777. * @param mc the context to use.
  778. * @throws ArithmeticException if the result is inexact but the
  779. * rounding mode is <tt>UNNECESSARY</tt>.
  780. * @since 1.5
  781. */
  782. public BigDecimal(int val, MathContext mc) {
  783. intVal = BigInteger.valueOf(val);
  784. if (mc.precision > 0)
  785. roundThis(mc);
  786. }
  787. /**
  788. * Translates a <tt>long</tt> into a <tt>BigDecimal</tt>. The
  789. * scale of the <tt>BigDecimal</tt> is zero.
  790. *
  791. * @param val <tt>long</tt> value to be converted to <tt>BigDecimal</tt>.
  792. * @since 1.5
  793. */
  794. public BigDecimal(long val) {
  795. intVal = BigInteger.valueOf(val);
  796. }
  797. /**
  798. * Translates a <tt>long</tt> into a <tt>BigDecimal</tt>, with
  799. * rounding according to the context settings. The scale of the
  800. * <tt>BigDecimal</tt>, before any rounding, is zero.
  801. *
  802. * @param val <tt>long</tt> value to be converted to <tt>BigDecimal</tt>.
  803. * @param mc the context to use.
  804. * @throws ArithmeticException if the result is inexact but the
  805. * rounding mode is <tt>UNNECESSARY</tt>.
  806. * @since 1.5
  807. */
  808. public BigDecimal(long val, MathContext mc) {
  809. intVal = BigInteger.valueOf(val);
  810. if (mc.precision > 0)
  811. roundThis(mc);
  812. }
  813. // Static Factory Methods
  814. /**
  815. * Translates a <tt>long</tt> unscaled value and an
  816. * <tt>int</tt> scale into a <tt>BigDecimal</tt>. This
  817. * "static factory method" is provided in preference to
  818. * a (<tt>long</tt>, <tt>int</tt>) constructor because it
  819. * allows for reuse of frequently used <tt>BigDecimal</tt> values..
  820. *
  821. * @param unscaledVal unscaled value of the <tt>BigDecimal</tt>.
  822. * @param scale scale of the <tt>BigDecimal</tt>.
  823. * @return a <tt>BigDecimal</tt> whose value is
  824. * <tt>(unscaledVal × 10<sup>-scale</sup>)</tt>.
  825. */
  826. public static BigDecimal valueOf(long unscaledVal, int scale) {
  827. if (scale == 0) {
  828. if (unscaledVal == 0)
  829. return ZERO;
  830. if (unscaledVal == 1)
  831. return ONE;
  832. if (unscaledVal == 10)
  833. return TEN;
  834. }
  835. return new BigDecimal(BigInteger.valueOf(unscaledVal), scale);
  836. }
  837. /**
  838. * Translates a <tt>long</tt> value into a <tt>BigDecimal</tt>
  839. * with a scale of zero. This "static factory method"
  840. * is provided in preference to a (<tt>long</tt>) constructor
  841. * because it allows for reuse of frequently used
  842. * <tt>BigDecimal</tt> values.
  843. *
  844. * @param val value of the <tt>BigDecimal</tt>.
  845. * @return a <tt>BigDecimal</tt> whose value is <tt>val</tt>.
  846. */
  847. public static BigDecimal valueOf(long val) {
  848. return valueOf(val, 0);
  849. }
  850. /**
  851. * Translates a <tt>double</tt> into a <tt>BigDecimal</tt>, using
  852. * the <tt>double</tt>'s canonical string representation provided
  853. * by the {@link Double#toString(double)} method.
  854. *
  855. * <p><b>Note:</b> This is generally the preferred way to convert
  856. * a <tt>double</tt> (or <tt>float</tt>) into a
  857. * <tt>BigDecimal</tt>, as the value returned is equal to that
  858. * resulting from constructing a <tt>BigDecimal</tt> from the
  859. * result of using {@link Double#toString(double)}.
  860. *
  861. * @param val <tt>double</tt> to convert to a <tt>BigDecimal</tt>.
  862. * @return a <tt>BigDecimal</tt> whose value is equal to or approximately
  863. * equal to the value of <tt>val</tt>.
  864. * @throws NumberFormatException if <tt>val</tt> is infinite or NaN.
  865. * @since 1.5
  866. */
  867. public static BigDecimal valueOf(double val) {
  868. // Reminder: a zero double returns '0.0', so we cannot fastpath
  869. // to use the constant ZERO. This might be important enough to
  870. // justify a factory approach, a cache, or a few private
  871. // constants, later.
  872. return new BigDecimal(Double.toString(val));
  873. }
  874. // Arithmetic Operations
  875. /**
  876. * Returns a <tt>BigDecimal</tt> whose value is <tt>(this +
  877. * augend)</tt>, and whose scale is <tt>max(this.scale(),
  878. * augend.scale())</tt>.
  879. *
  880. * @param augend value to be added to this <tt>BigDecimal</tt>.
  881. * @return <tt>this + augend</tt>
  882. */
  883. public BigDecimal add(BigDecimal augend) {
  884. BigDecimal arg[] = new BigDecimal[2];
  885. arg[0] = this; arg[1] = augend;
  886. matchScale(arg);
  887. return new BigDecimal(arg[0].intVal.add(arg[1].intVal), arg[0].scale);
  888. }
  889. /**
  890. * Returns a <tt>BigDecimal</tt> whose value is <tt>(this + augend)</tt>,
  891. * with rounding according to the context settings.
  892. *
  893. * If either number is zero and the precision setting is nonzero then
  894. * the other number, rounded if necessary, is used as the result.
  895. *
  896. * @param augend value to be added to this <tt>BigDecimal</tt>.
  897. * @param mc the context to use.
  898. * @return <tt>this + augend</tt>, rounded as necessary.
  899. * @throws ArithmeticException if the result is inexact but the
  900. * rounding mode is <tt>UNNECESSARY</tt>.
  901. * @since 1.5
  902. */
  903. public BigDecimal add(BigDecimal augend, MathContext mc) {
  904. if (mc.precision == 0)
  905. return add(augend);
  906. BigDecimal lhs = this;
  907. // If either number is zero then the other number, rounded and
  908. // scaled if necessary, is used as the result.
  909. {
  910. boolean lhsIsZero = lhs.signum() == 0;
  911. boolean augendIsZero = augend.signum() == 0;
  912. if (lhsIsZero || augendIsZero) {
  913. int preferredScale = Math.max(lhs.scale(), augend.scale());
  914. BigDecimal result;
  915. if (lhsIsZero && augendIsZero)
  916. return new BigDecimal(BigInteger.ZERO, preferredScale);
  917. result = lhsIsZero ? augend.doRound(mc) : lhs.doRound(mc);
  918. if (result.scale() == preferredScale)
  919. return result;
  920. else if (result.scale() > preferredScale)
  921. return result.stripZerosToMatchScale(preferredScale);
  922. else { // result.scale < preferredScale
  923. int precisionDiff = mc.precision - result.precision();
  924. int scaleDiff = preferredScale - result.scale();
  925. if (precisionDiff >= scaleDiff)
  926. return result.setScale(preferredScale); // can achieve target scale
  927. else
  928. return result.setScale(result.scale() + precisionDiff);
  929. }
  930. }
  931. }
  932. int padding = checkScale((long)lhs.scale - augend.scale);
  933. if (padding != 0) { // scales differ; alignment needed
  934. // if one operand is < 0.01 ulp of the other at full
  935. // precision, replace it by a 'sticky bit' of +0.001/-0.001 ulp.
  936. // [In a sense this is an 'optimization', but it also makes
  937. // a much wider range of additions practical.]
  938. if (padding < 0) { // lhs will be padded
  939. int ulpscale = lhs.scale - lhs.precision + mc.precision;
  940. if (augend.scale - augend.precision() > ulpscale + 1) {
  941. augend = BigDecimal.valueOf(augend.signum(), ulpscale + 3);
  942. }
  943. } else { // rhs (augend) will be padded
  944. int ulpscale = augend.scale - augend.precision + mc.precision;
  945. if (lhs.scale - lhs.precision() > ulpscale + 1)
  946. lhs = BigDecimal.valueOf(lhs.signum(), ulpscale + 3);
  947. }
  948. BigDecimal arg[] = new BigDecimal[2];
  949. arg[0] = lhs; arg[1] = augend;
  950. matchScale(arg);
  951. lhs = arg[0];
  952. augend = arg[1];
  953. }
  954. return new BigDecimal(lhs.intVal.add(augend.intVal), lhs.scale).doRound(mc);
  955. }
  956. /**
  957. * Returns a <tt>BigDecimal</tt> whose value is <tt>(this -
  958. * subtrahend)</tt>, and whose scale is <tt>max(this.scale(),
  959. * subtrahend.scale())</tt>.
  960. *
  961. * @param subtrahend value to be subtracted from this <tt>BigDecimal</tt>.
  962. * @return <tt>this - subtrahend</tt>
  963. */
  964. public BigDecimal subtract(BigDecimal subtrahend) {
  965. BigDecimal arg[] = new BigDecimal[2];
  966. arg[0] = this; arg[1] = subtrahend;
  967. matchScale(arg);
  968. return new BigDecimal(arg[0].intVal.subtract(arg[1].intVal),
  969. arg[0].scale);
  970. }
  971. /**
  972. * Returns a <tt>BigDecimal</tt> whose value is <tt>(this - subtrahend)</tt>,
  973. * with rounding according to the context settings.
  974. *
  975. * If <tt>subtrahend</tt> is zero then this, rounded if necessary, is used as the
  976. * result. If this is zero then the result is <tt>subtrahend.negate(mc)</tt>.
  977. *
  978. * @param subtrahend value to be subtracted from this <tt>BigDecimal</tt>.
  979. * @param mc the context to use.
  980. * @return <tt>this - subtrahend</tt>, rounded as necessary.
  981. * @throws ArithmeticException if the result is inexact but the
  982. * rounding mode is <tt>UNNECESSARY</tt>.
  983. * @since 1.5
  984. */
  985. public BigDecimal subtract(BigDecimal subtrahend, MathContext mc) {
  986. if (mc.precision == 0)
  987. return subtract(subtrahend);
  988. // share the special rounding code in add()
  989. BigDecimal rhs = new BigDecimal(subtrahend.intVal.negate(), subtrahend.scale);
  990. rhs.precision = subtrahend.precision;
  991. return add(rhs, mc);
  992. }
  993. /**
  994. * Returns a <tt>BigDecimal</tt> whose value is <tt>(this ×
  995. * multiplicand)</tt>, and whose scale is <tt>(this.scale() +
  996. * multiplicand.scale())</tt>.
  997. *
  998. * @param multiplicand value to be multiplied by this <tt>BigDecimal</tt>.
  999. * @return <tt>this * multiplicand</tt>
  1000. */
  1001. public BigDecimal multiply(BigDecimal multiplicand) {
  1002. BigDecimal result = new BigDecimal(intVal.multiply(multiplicand.intVal), 0);
  1003. result.scale = checkScale((long)scale+multiplicand.scale);
  1004. return result;
  1005. }
  1006. /**
  1007. * Returns a <tt>BigDecimal</tt> whose value is <tt>(this ×
  1008. * multiplicand)</tt>, with rounding according to the context settings.
  1009. *
  1010. * @param multiplicand value to be multiplied by this <tt>BigDecimal</tt>.
  1011. * @param mc the context to use.
  1012. * @return <tt>this * multiplicand</tt>, rounded as necessary.
  1013. * @throws ArithmeticException if the result is inexact but the
  1014. * rounding mode is <tt>UNNECESSARY</tt>.
  1015. * @since 1.5
  1016. */
  1017. public BigDecimal multiply(BigDecimal multiplicand, MathContext mc) {
  1018. if (mc.precision == 0)
  1019. return multiply(multiplicand);
  1020. BigDecimal lhs = this;
  1021. return lhs.multiply(multiplicand).doRound(mc);
  1022. }
  1023. /**
  1024. * Returns a <tt>BigDecimal</tt> whose value is <tt>(this /
  1025. * divisor)</tt>, and whose scale is as specified. If rounding must
  1026. * be performed to generate a result with the specified scale, the
  1027. * specified rounding mode is applied.
  1028. *
  1029. * <p>The new {@link #divide(BigDecimal, int, RoundingMode)} method
  1030. * should be used in preference to this legacy method.
  1031. *
  1032. * @param divisor value by which this <tt>BigDecimal</tt> is to be divided.
  1033. * @param scale scale of the <tt>BigDecimal</tt> quotient to be returned.
  1034. * @param roundingMode rounding mode to apply.
  1035. * @return <tt>this / divisor</tt>
  1036. * @throws ArithmeticException if <tt>divisor</tt> is zero,
  1037. * <tt>roundingMode==ROUND_UNNECESSARY</tt> and
  1038. * the specified scale is insufficient to represent the result
  1039. * of the division exactly.
  1040. * @throws IllegalArgumentException if <tt>roundingMode</tt> does not
  1041. * represent a valid rounding mode.
  1042. * @see #ROUND_UP
  1043. * @see #ROUND_DOWN
  1044. * @see #ROUND_CEILING
  1045. * @see #ROUND_FLOOR
  1046. * @see #ROUND_HALF_UP
  1047. * @see #ROUND_HALF_DOWN
  1048. * @see #ROUND_HALF_EVEN
  1049. * @see #ROUND_UNNECESSARY
  1050. */
  1051. public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode) {
  1052. if (roundingMode < ROUND_UP || roundingMode > ROUND_UNNECESSARY)
  1053. throw new IllegalArgumentException("Invalid rounding mode");
  1054. /*
  1055. * Rescale dividend or divisor (whichever can be "upscaled" to
  1056. * produce correctly scaled quotient).
  1057. * Take care to detect out-of-range scales
  1058. */
  1059. BigDecimal dividend;
  1060. if (checkScale((long)scale + divisor.scale) >= this.scale) {
  1061. dividend = this.setScale(scale + divisor.scale);
  1062. } else {
  1063. dividend = this;
  1064. divisor = divisor.setScale(checkScale((long)this.scale - scale));
  1065. }
  1066. /* Do the division and return result if it's exact */
  1067. BigInteger i[] = dividend.intVal.divideAndRemainder(divisor.intVal);
  1068. BigInteger q = i[0], r = i[1];
  1069. if (r.signum() == 0)
  1070. return new BigDecimal(q, scale);
  1071. if (roundingMode == ROUND_UNNECESSARY) /* Rounding prohibited */
  1072. throw new ArithmeticException("Rounding necessary");
  1073. /* Round as appropriate */
  1074. int signum = dividend.signum() * divisor.signum(); /* Sign of result */
  1075. boolean increment;
  1076. if (roundingMode == ROUND_UP) { /* Away from zero */
  1077. increment = true;
  1078. } else if (roundingMode == ROUND_DOWN) { /* Towards zero */
  1079. increment = false;
  1080. } else if (roundingMode == ROUND_CEILING) { /* Towards +infinity */
  1081. increment = (signum > 0);
  1082. } else if (roundingMode == ROUND_FLOOR) { /* Towards -infinity */
  1083. increment = (signum < 0);
  1084. } else { /* Remaining modes based on nearest-neighbor determination */
  1085. // add(r) here is faster than multiply(2) or shiftLeft(1)
  1086. int cmpFracHalf = r.add(r).abs().compareTo(divisor.intVal.abs());
  1087. if (cmpFracHalf < 0) { /* We're closer to higher digit */
  1088. increment = false;
  1089. } else if (cmpFracHalf > 0) { /* We're closer to lower digit */
  1090. increment = true;
  1091. } else { /* We're dead-center */
  1092. if (roundingMode == ROUND_HALF_UP)
  1093. increment = true;
  1094. else if (roundingMode == ROUND_HALF_DOWN)
  1095. increment = false;
  1096. else /* roundingMode == ROUND_HALF_EVEN */
  1097. increment = q.testBit(0); /* true iff q is odd */
  1098. }
  1099. }
  1100. return (increment
  1101. ? new BigDecimal(q.add(BigInteger.valueOf(signum)), scale)
  1102. : new BigDecimal(q, scale));
  1103. }
  1104. /**
  1105. * Returns a <tt>BigDecimal</tt> whose value is <tt>(this /
  1106. * divisor)</tt>, and whose scale is as specified. If rounding must
  1107. * be performed to generate a result with the specified scale, the
  1108. * specified rounding mode is applied.
  1109. *
  1110. * @param divisor value by which this <tt>BigDecimal</tt> is to be divided.
  1111. * @param scale scale of the <tt>BigDecimal</tt> quotient to be returned.
  1112. * @param roundingMode rounding mode to apply.
  1113. * @return <tt>this / divisor</tt>
  1114. * @throws ArithmeticException if <tt>divisor</tt> is zero,
  1115. * <tt>roundingMode==RoundingMode.UNNECESSARY</tt> and
  1116. * the specified scale is insufficient to represent the result
  1117. * of the division exactly.
  1118. * @since 1.5
  1119. */
  1120. public BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode) {
  1121. return divide(divisor, scale, roundingMode.oldMode);
  1122. }
  1123. /**
  1124. * Returns a <tt>BigDecimal</tt> whose value is <tt>(this /
  1125. * divisor)</tt>, and whose scale is <tt>this.scale()</tt>. If
  1126. * rounding must be performed to generate a result with the given
  1127. * scale, the specified rounding mode is applied.
  1128. *
  1129. * <p>The new {@link #divide(BigDecimal, RoundingMode)} method
  1130. * should be used in preference to this legacy method.
  1131. *
  1132. * @param divisor value by which this <tt>BigDecimal</tt> is to be divided.
  1133. * @param roundingMode rounding mode to apply.
  1134. * @return <tt>this / divisor</tt>
  1135. * @throws ArithmeticException if <tt>divisor==0</tt>, or
  1136. * <tt>roundingMode==ROUND_UNNECESSARY</tt> and
  1137. * <tt>this.scale()</tt> is insufficient to represent the result
  1138. * of the division exactly.
  1139. * @throws IllegalArgumentException if <tt>roundingMode</tt> does not
  1140. * represent a valid rounding mode.
  1141. * @see #ROUND_UP
  1142. * @see #ROUND_DOWN
  1143. * @see #ROUND_CEILING
  1144. * @see #ROUND_FLOOR
  1145. * @see #ROUND_HALF_UP
  1146. * @see #ROUND_HALF_DOWN
  1147. * @see #ROUND_HALF_EVEN
  1148. * @see #ROUND_UNNECESSARY
  1149. */
  1150. public BigDecimal divide(BigDecimal divisor, int roundingMode) {
  1151. return this.divide(divisor, scale, roundingMode);
  1152. }
  1153. /**
  1154. * Returns a <tt>BigDecimal</tt> whose value is <tt>(this /
  1155. * divisor)</tt>, and whose scale is <tt>this.scale()</tt>. If
  1156. * rounding must be performed to generate a result with the given
  1157. * scale, the specified rounding mode is applied.
  1158. *
  1159. * @param divisor value by which this <tt>BigDecimal</tt> is to be divided.
  1160. * @param roundingMode rounding mode to apply.
  1161. * @return <tt>this / divisor</tt>
  1162. * @throws ArithmeticException if <tt>divisor==0</tt>, or
  1163. * <tt>roundingMode==RoundingMode.UNNECESSARY</tt> and
  1164. * <tt>this.scale()</tt> is insufficient to represent the result
  1165. * of the division exactly.
  1166. */
  1167. public BigDecimal divide(BigDecimal divisor, RoundingMode roundingMode) {
  1168. return this.divide(divisor, scale, roundingMode.oldMode);
  1169. }
  1170. /**
  1171. * Returns a <tt>BigDecimal</tt> whose value is <tt>(this /
  1172. * divisor)</tt>, and whose preferred scale is <tt>(this.scale() -
  1173. * divisor.scale())</tt> if the exact quotient cannot be
  1174. * represented (because it has a non-terminating decimal
  1175. * expansion) an <tt>ArithmeticException</tt> is thrown.
  1176. *
  1177. * @param divisor value by which this <tt>BigDecimal</tt> is to be divided.
  1178. * @throws ArithmeticException if the exact quotient does not have a
  1179. * terminating decimal expansion
  1180. * @return <tt>this / divisor</tt>
  1181. * @since 1.5
  1182. * @author Joseph D. Darcy
  1183. */
  1184. public BigDecimal divide(BigDecimal divisor) {
  1185. /*
  1186. * Handle zero cases first.
  1187. */
  1188. if (divisor.intVal.signum() == 0) { // x/0
  1189. if (this.intVal.signum() == 0) // 0/0
  1190. throw new ArithmeticException("Division undefined"); // NaN
  1191. throw new ArithmeticException("Division by zero");
  1192. }
  1193. // Calculate preferred scale
  1194. int preferredScale = (int)Math.max(Math.min((long)this.scale() - divisor.scale(),
  1195. Integer.MAX_VALUE), Integer.MIN_VALUE);
  1196. if (this.intVal.signum() == 0) // 0/y
  1197. return BigDecimal.valueOf(0, preferredScale);
  1198. else {
  1199. /*
  1200. * If the quotient this/divisor has a terminating decimal
  1201. * expansion, the expansion can have no more than
  1202. * (a.precision() + ceil(10*b.precision)/3) digits.
  1203. * Therefore, create a MathContext object with this
  1204. * precision and do a divide with the UNNECESSARY rounding
  1205. * mode.
  1206. */
  1207. MathContext mc = new MathContext( (int)Math.min(this.precision() +
  1208. (long)Math.ceil(10.0*divisor.precision()/3.0),
  1209. Integer.MAX_VALUE),
  1210. RoundingMode.UNNECESSARY);
  1211. BigDecimal quotient;
  1212. try {
  1213. quotient = this.divide(divisor, mc);
  1214. } catch (ArithmeticException e) {
  1215. throw new ArithmeticException("Non-terminating decimal expansion; " +
  1216. "no exact representable decimal result.");
  1217. }
  1218. int quotientScale = quotient.scale();
  1219. // divide(BigDecimal, mc) tries to adjust the quotient to
  1220. // the desired one by removing trailing zeros; since the
  1221. // exact divide method does not have an explicit digit
  1222. // limit, we can add zeros too.
  1223. if (preferredScale > quotientScale)
  1224. return quotient.setScale(preferredScale);
  1225. return quotient;
  1226. }
  1227. }
  1228. /**
  1229. * Returns a <tt>BigDecimal</tt> whose value is <tt>(this /
  1230. * divisor)</tt>, with rounding according to the context settings.
  1231. *
  1232. * @param divisor value by which this <tt>BigDecimal</tt> is to be divided.
  1233. * @param mc the context to use.
  1234. * @return <tt>this / divisor</tt>, rounded as necessary.
  1235. * @throws ArithmeticException if the result is inexact but the
  1236. * rounding mode is <tt>UNNECESSARY</tt> or
  1237. * <tt>mc.precision == 0</tt> and the quotient has a
  1238. * non-terminating decimal expansion.
  1239. * @since 1.5
  1240. */
  1241. public BigDecimal divide(BigDecimal divisor, MathContext mc) {
  1242. if (mc.precision == 0)
  1243. return divide(divisor);
  1244. BigDecimal lhs = this; // left-hand-side
  1245. BigDecimal rhs = divisor; // right-hand-side
  1246. BigDecimal result; // work
  1247. long preferredScale = (long)lhs.scale() - rhs.scale();
  1248. // Now calculate the answer. We use the existing
  1249. // divide-and-round method, but as this rounds to scale we have
  1250. // to normalize the values here to achieve the desired result.
  1251. // For x/y we first handle y=0 and x=0, and then normalize x and
  1252. // y to give x' and y' with the following constraints:
  1253. // (a) 0.1 <= x' < 1
  1254. // (b) x' <= y' < 10*x'
  1255. // Dividing x'/y' with the required scale set to mc.precision then
  1256. // will give a result in the range 0.1 to 1 rounded to exactly
  1257. // the right number of digits (except in the case of a result of
  1258. // 1.000... which can arise when x=y, or when rounding overflows
  1259. // The 1.000... case will reduce properly to 1.
  1260. if (rhs.intVal.signum() == 0) { // x/0
  1261. if (lhs.intVal.signum() == 0) // 0/0
  1262. throw new ArithmeticException("Division undefined"); // NaN
  1263. throw new ArithmeticException("Division by zero");
  1264. }
  1265. if (lhs.intVal.signum() == 0) // 0/y
  1266. return new BigDecimal(BigInteger.ZERO,
  1267. (int)Math.max(Math.min(preferredScale,
  1268. Integer.MAX_VALUE),
  1269. Integer.MIN_VALUE));
  1270. BigDecimal xprime = new BigDecimal(lhs.intVal.abs(), lhs.precision());
  1271. BigDecimal yprime = new BigDecimal(rhs.intVal.abs(), rhs.precision());
  1272. // xprime and yprime are now both in range 0.1 through 0.999...
  1273. if (mc.roundingMode == RoundingMode.CEILING ||
  1274. mc.roundingMode == RoundingMode.FLOOR) {
  1275. // The floor (round toward negative infinity) and ceil
  1276. // (round toward positive infinity) rounding modes are not
  1277. // invariant under a sign flip. If xprime/yprime has a
  1278. // different sign than lhs/rhs, the rounding mode must be
  1279. // changed.
  1280. if ((xprime.signum() != lhs.signum()) ^
  1281. (yprime.signum() != rhs.signum())) {
  1282. mc = new MathContext(mc.precision,
  1283. (mc.roundingMode==RoundingMode.CEILING)?
  1284. RoundingMode.FLOOR:RoundingMode.CEILING);
  1285. }
  1286. }
  1287. if (xprime.compareTo(yprime) > 0) // satisfy constraint (b)
  1288. yprime.scale -= 1; // [that is, yprime *= 10]
  1289. result = xprime.divide(yprime, mc.precision, mc.roundingMode.oldMode);
  1290. // correct the scale of the result...
  1291. result.scale = checkScale((long)yprime.scale - xprime.scale
  1292. - (rhs.scale - lhs.scale) + mc.precision);
  1293. // apply the sign
  1294. if (lhs.intVal.signum() != rhs.intVal.signum())
  1295. result = result.negate();
  1296. // doRound, here, only affects 1000000000 case.
  1297. result = result.doRound(mc);
  1298. if (result.multiply(divisor).compareTo(this) == 0) {
  1299. // Apply preferred scale rules for exact quotients
  1300. return result.stripZerosToMatchScale(preferredScale);
  1301. }
  1302. else {
  1303. return result;
  1304. }
  1305. }
  1306. /**
  1307. * Returns a <tt>BigDecimal</tt> whose value is the integer part
  1308. * of the quotient <tt>(this / divisor)</tt> rounded down. The
  1309. * preferred scale of the result is <code>(this.scale() -
  1310. * divisor.scale())</code>.
  1311. *
  1312. * @param divisor value by which this <tt>BigDecimal</tt> is to be divided.
  1313. * @return The integer part of <tt>this / divisor</tt>.
  1314. * @throws ArithmeticException if <tt>divisor==0</tt>
  1315. * @since 1.5
  1316. */
  1317. public BigDecimal divideToIntegralValue(BigDecimal divisor) {
  1318. // Calculate preferred scale
  1319. int preferredScale = (int)Math.max(Math.min((long)this.scale() - divisor.scale(),
  1320. Integer.MAX_VALUE), Integer.MIN_VALUE);
  1321. if (this.abs().compareTo(divisor.abs()) < 0) {
  1322. // much faster when this << divisor
  1323. return BigDecimal.valueOf(0, preferredScale);
  1324. }
  1325. if(this.signum() == 0 && divisor.signum() != 0)
  1326. return this.setScale(preferredScale);
  1327. // Perform a divide with enough digits to round to a correct
  1328. // integer value; then remove any fractional digits
  1329. int maxDigits = (int)Math.min(this.precision() +
  1330. (long)Math.ceil(10.0*divisor.precision()/3.0) +
  1331. Math.abs((long)this.scale() - divisor.scale()) + 2,
  1332. Integer.MAX_VALUE);
  1333. BigDecimal quotient = this.divide(divisor, new MathContext(maxDigits,
  1334. RoundingMode.DOWN));
  1335. if (quotient.scale > 0) {
  1336. quotient = quotient.setScale(0, RoundingMode.DOWN).
  1337. stripZerosToMatchScale(preferredScale);
  1338. }
  1339. if (quotient.scale < preferredScale) {
  1340. // pad with zeros if necessary
  1341. quotient = quotient.setScale(preferredScale);
  1342. }
  1343. return quotient;
  1344. }
  1345. /**
  1346. * Returns a <tt>BigDecimal</tt> whose value is the integer part
  1347. * of <tt>(this / divisor)</tt>. Since the integer part of the
  1348. * exact quotient does not depend on the rounding mode, the
  1349. * rounding mode does not affect the values returned by this
  1350. * method. The preferred scale of the result is
  1351. * <code>(this.scale() - divisor.scale())</code>. An
  1352. * <tt>ArithmeticException</tt> is thrown if the integer part of
  1353. * the exact quotient needs more than <tt>mc.precision</tt>
  1354. * digits.
  1355. *
  1356. * @param divisor value by which this <tt>BigDecimal</tt> is to be divided.
  1357. * @param mc the context to use.
  1358. * @return The integer part of <tt>this / divisor</tt>.
  1359. * @throws ArithmeticException if <tt>divisor==0</tt>
  1360. * @throws ArithmeticException if <tt>mc.precision</tt> > 0 and the result
  1361. * requires a precision of more than <tt>mc.precision</tt> digits.
  1362. * @since 1.5
  1363. * @author Joseph D. Darcy
  1364. */
  1365. public BigDecimal divideToIntegralValue(BigDecimal divisor, MathContext mc) {
  1366. if (mc.precision == 0 || // exact result
  1367. (this.abs().compareTo(divisor.abs()) < 0) ) // zero result
  1368. return divideToIntegralValue(divisor);
  1369. // Calculate preferred scale
  1370. int preferredScale = (int)Math.max(Math.min((long)this.scale() - divisor.scale(),
  1371. Integer.MAX_VALUE), Integer.MIN_VALUE);
  1372. /*
  1373. * Perform a normal divide to mc.precision digits. If the
  1374. * remainder has absolute value less than the divisor, the
  1375. * integer portion of the quotient fits into mc.precision
  1376. * digits. Next, remove any fractional digits from the
  1377. * quotient and adjust the scale to the preferred value.
  1378. */
  1379. BigDecimal result = this.divide(divisor, new MathContext(mc.precision,
  1380. RoundingMode.DOWN));
  1381. int resultScale = result.scale();
  1382. if (result.scale() < 0) {
  1383. /*
  1384. * Result is an integer. See if quotient represents the
  1385. * full integer portion of the exact quotient; if it does,
  1386. * the computed remainder will be less than the divisor.
  1387. */
  1388. BigDecimal product = result.multiply(divisor);
  1389. if (this.subtract(product).abs().compareTo(divisor.abs()) > 0) {
  1390. throw new ArithmeticException("Division impossible");
  1391. }
  1392. } else if (result.scale() > 0) {
  1393. /*
  1394. * Integer portion of quotient will fit into precision
  1395. * digits; recompute quotient to scale 0 to avoid double
  1396. * rounding and then try to adjust, if necessary.
  1397. */
  1398. result = result.setScale(0, RoundingMode.DOWN);
  1399. }
  1400. // else result.scale() == 0;
  1401. int precisionDiff;
  1402. if ((preferredScale > result.scale()) &&
  1403. (precisionDiff = mc.precision - result.precision()) > 0 ) {
  1404. return result.setScale(result.scale() +
  1405. Math.min(precisionDiff, preferredScale - result.scale) );
  1406. } else
  1407. return result.stripZerosToMatchScale(preferredScale);
  1408. }
  1409. /**
  1410. * Returns a <tt>BigDecimal</tt> whose value is <tt>(this % divisor)</tt>.
  1411. *
  1412. * <p>The remainder is given by
  1413. * <tt>this.subtract(this.divideToIntegralValue(divisor).multiply(divisor))</tt>.
  1414. * Note that this is not the modulo operation (the result can be
  1415. * negative).
  1416. *
  1417. * @param divisor value by which this <tt>BigDecimal</tt> is to be divided.
  1418. * @return <tt>this % divisor</tt>.
  1419. * @throws ArithmeticException if <tt>divisor==0</tt>
  1420. * @since 1.5
  1421. */
  1422. public BigDecimal remainder(BigDecimal divisor) {
  1423. BigDecimal divrem[] = this.divideAndRemainder(divisor);
  1424. return divrem[1];
  1425. }
  1426. /**
  1427. * Returns a <tt>BigDecimal</tt> whose value is <tt>(this %
  1428. * divisor)</tt>, with rounding according to the context settings.
  1429. * The <tt>MathContext</tt> settings affect the implicit divide
  1430. * used to compute the remainder. The remainder computation
  1431. * itself is by definition exact. Therefore, the remainder may
  1432. * contain more than <tt>mc.getPrecision()</tt> digits.
  1433. *
  1434. * <p>The remainder is given by
  1435. * <tt>this.subtract(this.divideToIntegralValue(divisor,
  1436. * mc).multiply(divisor))</tt>. Note that this is not the modulo
  1437. * operation (the result can be negative).
  1438. *
  1439. * @param divisor value by which this <tt>BigDecimal</tt> is to be divided.
  1440. * @param mc the context to use.
  1441. * @return <tt>this % divisor</tt>, rounded as necessary.
  1442. * @throws ArithmeticException if <tt>divisor==0</tt>
  1443. * @throws ArithmeticException if the result is inexact but the
  1444. * rounding mode is <tt>UNNECESSARY</tt>, or <tt>mc.precision</tt>
  1445. * > 0 and the result of <tt>this.divideToIntgralValue(divisor)</tt> would
  1446. * require a precision of more than <tt>mc.precision</tt> digits.
  1447. * @see #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext)
  1448. * @since 1.5
  1449. */
  1450. public BigDecimal remainder(BigDecimal divisor, MathContext mc) {
  1451. BigDecimal divrem[] = this.divideAndRemainder(divisor, mc);
  1452. return divrem[1];
  1453. }
  1454. /**
  1455. * Returns a two-element <tt>BigDecimal</tt> array containing the
  1456. * result of <tt>divideToIntegralValue</tt> followed by the result of
  1457. * <tt>remainder</tt> on the two operands.
  1458. *
  1459. * <p>Note that if both the integer quotient and remainder are
  1460. * needed, this method is faster than using the
  1461. * <tt>divideToIntegralValue</tt> and <tt>remainder</tt> methods
  1462. * separately because the division need only be carried out once.
  1463. *
  1464. * @param divisor value by which this <tt>BigDecimal</tt> is to be divided,
  1465. * and the remainder computed.
  1466. * @return a two element <tt>BigDecimal</tt> array: the quotient
  1467. * (the result of <tt>divideToIntegralValue</tt>) is the initial element
  1468. * and the remainder is the final element.
  1469. * @throws ArithmeticException if <tt>divisor==0</tt>
  1470. * @see #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext)
  1471. * @see #remainder(java.math.BigDecimal, java.math.MathContext)
  1472. * @since 1.5
  1473. */
  1474. public BigDecimal[] divideAndRemainder(BigDecimal divisor) {
  1475. // we use the identity x = i * y + r to determine r
  1476. BigDecimal[] result = new BigDecimal[2];
  1477. result[0] = this.divideToIntegralValue(divisor);
  1478. result[1] = this.subtract(result[0].multiply(divisor));
  1479. return result;
  1480. }
  1481. /**
  1482. * Returns a two-element <tt>BigDecimal</tt> array containing the
  1483. * result of <tt>divideToIntegralValue</tt> followed by the result of
  1484. * <tt>remainder</tt> on the two operands calculated with rounding
  1485. * according to the context settings.
  1486. *
  1487. * <p>Note that if both the integer quotient and remainder are
  1488. * needed, this method is faster than using the
  1489. * <tt>divideToIntegralValue</tt> and <tt>remainder</tt> methods
  1490. * separately because the division need only be carried out once.
  1491. *
  1492. * @param divisor value by which this <tt>BigDecimal</tt> is to be divided,
  1493. * and the remainder computed.
  1494. * @param mc the context to use.
  1495. * @return a two element <tt>BigDecimal</tt> array: the quotient
  1496. * (the result of <tt>divideToIntegralValue</tt>) is the
  1497. * initial element and the remainder is the final element.
  1498. * @throws ArithmeticException if <tt>divisor==0</tt>
  1499. * @throws ArithmeticException if the result is inexact but the
  1500. * rounding mode is <tt>UNNECESSARY</tt>, or <tt>mc.precision</tt>
  1501. * > 0 and the result of <tt>this.divideToIntgralValue(divisor)</tt> would
  1502. * require a precision of more than <tt>mc.precision</tt> digits.
  1503. * @see #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext)
  1504. * @see #remainder(java.math.BigDecimal, java.math.MathContext)
  1505. * @since 1.5
  1506. */
  1507. public BigDecimal[] divideAndRemainder(BigDecimal divisor, MathContext mc) {
  1508. if (mc.precision == 0)
  1509. return divideAndRemainder(divisor);
  1510. BigDecimal[] result = new BigDecimal[2];
  1511. BigDecimal lhs = this;
  1512. result[0] = lhs.divideToIntegralValue(divisor, mc);
  1513. result[1] = lhs.subtract(result[0].multiply(divisor));
  1514. return result;
  1515. }
  1516. /**
  1517. * Returns a <tt>BigDecimal</tt> whose value is
  1518. * <tt>(this<sup>n</sup>)</tt>, The power is computed exactly, to
  1519. * unlimited precision.
  1520. *
  1521. * <p>The parameter <tt>n</tt> must be in the range 0 through
  1522. * 999999999, inclusive. <tt>ZERO.pow(0)</tt> returns {@link
  1523. * #ONE}.
  1524. *
  1525. * Note that future releases may expand the allowable exponent
  1526. * range of this method.
  1527. *
  1528. * @param n power to raise this <tt>BigDecimal</tt> to.
  1529. * @return <tt>this<sup>n</sup></tt>
  1530. * @throws ArithmeticException if <tt>n</tt> is out of range.
  1531. * @since 1.5
  1532. */
  1533. public BigDecimal pow(int n) {
  1534. if (n < 0 || n > 999999999)
  1535. throw new ArithmeticException("Invalid operation");
  1536. // No need to calculate pow(n) if result will over/underflow.
  1537. // Don't attempt to support "supernormal" numbers.
  1538. int newScale = checkScale((long)scale * n);
  1539. return new BigDecimal(intVal.pow(n), newScale);
  1540. }
  1541. /**
  1542. * Returns a <tt>BigDecimal</tt> whose value is
  1543. * <tt>(this<sup>n</sup>)</tt>. The current implementation uses
  1544. * the core algorithm defined in ANSI standard X3.274-1996 with
  1545. * rounding according to the context settings. In general, the
  1546. * returned numerical value is within two ulps of the exact
  1547. * numerical value for the chosen precision. Note that future
  1548. * releases may use a different algorithm with a decreased
  1549. * allowable error bound and increased allowable exponent range.
  1550. *
  1551. * <p>The X3.274-1996 algorithm is:
  1552. *
  1553. * <ul>
  1554. * <li> An <tt>ArithmeticException</tt> exception is thrown if
  1555. * <ul>
  1556. * <li><tt>abs(n) > 999999999</tt>
  1557. * <li><tt>mc.precision == 0</tt> and <tt>n < 0</tt>
  1558. * <li><tt>mc.precision > 0</tt> and <tt>n</tt> has more than
  1559. * <tt>mc.precision</tt> decimal digits
  1560. * </ul>
  1561. *
  1562. * <li> if <tt>n</tt> is zero, {@link #ONE} is returned even if
  1563. * <tt>this</tt> is zero, otherwise
  1564. * <ul>
  1565. * <li> if <tt>n</tt> is positive, the result is calculated via
  1566. * the repeated squaring technique into a single accumulator.
  1567. * The individual multiplications with the accumulator use the
  1568. * same math context settings as in <tt>mc</tt> except for a
  1569. * precision increased to <tt>mc.precision + elength + 1</tt>
  1570. * where <tt>elength</tt> is the number of decimal digits in
  1571. * <tt>n</tt>.
  1572. *
  1573. * <li> if <tt>n</tt> is negative, the result is calculated as if
  1574. * <tt>n</tt> were positive; this value is then divided into one
  1575. * using the working precision specified above.
  1576. *
  1577. * <li> The final value from either the positive or negative case
  1578. * is then rounded to the destination precision.
  1579. * </ul>
  1580. * </ul>
  1581. *
  1582. * @param n power to raise this <tt>BigDecimal</tt> to.
  1583. * @param mc the context to use.
  1584. * @return <tt>this<sup>n</sup></tt> using the ANSI standard X3.274-1996
  1585. * algorithm
  1586. * @throws ArithmeticException if the result is inexact but the
  1587. * rounding mode is <tt>UNNECESSARY</tt>, or <tt>n</tt> is out
  1588. * of range.
  1589. * @since 1.5
  1590. */
  1591. public BigDecimal pow(int n, MathContext mc) {
  1592. if (mc.precision == 0)
  1593. return pow(n);
  1594. if (n < -999999999 || n > 999999999)
  1595. throw new ArithmeticException("Invalid operation");
  1596. if (n == 0)
  1597. return ONE; // x**0 == 1 in X3.274
  1598. BigDecimal lhs = this;
  1599. MathContext workmc = mc; // working settings
  1600. int mag = Math.abs(n); // magnitude of n
  1601. if (mc.precision > 0) {
  1602. int elength = intLength(mag); // length of n in digits
  1603. if (elength > mc.precision) // X3.274 rule
  1604. throw new ArithmeticException("Invalid operation");
  1605. workmc = new MathContext(mc.precision + elength + 1,
  1606. mc.roundingMode);
  1607. }
  1608. // ready to carry out power calculation...
  1609. BigDecimal acc = ONE; // accumulator
  1610. boolean seenbit = false; // set once we've seen a 1-bit
  1611. for (int i=1;;i++) { // for each bit [top bit ignored]
  1612. mag += mag; // shift left 1 bit
  1613. if (mag < 0) { // top bit is set
  1614. seenbit = true; // OK, we're off
  1615. acc = acc.multiply(lhs, workmc); // acc=acc*x
  1616. }
  1617. if (i == 31)
  1618. break; // that was the last bit
  1619. if (seenbit)
  1620. acc=acc.multiply(acc, workmc); // acc=acc*acc [square]
  1621. // else (!seenbit) no point in squaring ONE
  1622. }
  1623. // if negative n, calculate the reciprocal using working precision
  1624. if (n<0) // [hence mc.precision>0]
  1625. acc=ONE.divide(acc, workmc);
  1626. // round to final precision and strip zeros
  1627. return acc.doRound(mc);
  1628. }
  1629. /**
  1630. * Returns a <tt>BigDecimal</tt> whose value is the absolute value
  1631. * of this <tt>BigDecimal</tt>, and whose scale is
  1632. * <tt>this.scale()</tt>.
  1633. *
  1634. * @return <tt>abs(this)</tt>
  1635. */
  1636. public BigDecimal abs() {
  1637. return (signum() < 0 ? negate() : this);
  1638. }
  1639. /**
  1640. * Returns a <tt>BigDecimal</tt> whose value is the absolute value
  1641. * of this <tt>BigDecimal</tt>, with rounding according to the
  1642. * context settings.
  1643. *
  1644. * @param mc the context to use.
  1645. * @return <tt>abs(this)</tt>, rounded as necessary.
  1646. * @throws ArithmeticException if the result is inexact but the
  1647. * rounding mode is <tt>UNNECESSARY</tt>.
  1648. */
  1649. public BigDecimal abs(MathContext mc) {
  1650. return (signum() < 0 ? negate(mc) : plus(mc));
  1651. }
  1652. /**
  1653. * Returns a <tt>BigDecimal</tt> whose value is <tt>(-this)</tt>,
  1654. * and whose scale is <tt>this.scale()</tt>.
  1655. *
  1656. * @return <tt>-this</tt>.
  1657. */
  1658. public BigDecimal negate() {
  1659. BigDecimal result = new BigDecimal(intVal.negate(), scale);
  1660. result.precision = precision;
  1661. return result;
  1662. }
  1663. /**
  1664. * Returns a <tt>BigDecimal</tt> whose value is <tt>(-this)</tt>,
  1665. * with rounding according to the context settings.
  1666. *
  1667. * @param mc the context to use.
  1668. * @return <tt>-this</tt>, rounded as necessary.
  1669. * @throws ArithmeticException if or the result is inexact but the
  1670. * rounding mode is <tt>UNNECESSARY</tt>.
  1671. * @since 1.5
  1672. */
  1673. public BigDecimal negate(MathContext mc) {
  1674. return plus(mc).negate();
  1675. }
  1676. /**
  1677. * Returns a <tt>BigDecimal</tt> whose value is <tt>(+this)</tt>, and whose
  1678. * scale is <tt>this.scale()</tt>.
  1679. *
  1680. * <p>This method, which simply returns this <tt>BigDecimal</tt>
  1681. * is included for symmetry with the unary minus method {@link
  1682. * #negate()}.
  1683. *
  1684. * @return <tt>this</tt>.
  1685. * @see #negate()
  1686. * @since 1.5
  1687. */
  1688. public BigDecimal plus() {
  1689. return this;
  1690. }
  1691. /**
  1692. * Returns a <tt>BigDecimal</tt> whose value is <tt>(+this)</tt>,
  1693. * with rounding according to the context settings.
  1694. *
  1695. * <p>The effect of this method is identical to that of the {@link
  1696. * #round(MathContext)} method.
  1697. *
  1698. * @param mc the context to use.
  1699. * @return <tt>this</tt>, rounded as necessary. A zero result will
  1700. * have a scale of 0.
  1701. * @throws ArithmeticException if the result is inexact but the
  1702. * rounding mode is <tt>UNNECESSARY</tt>.
  1703. * @see #round(MathContext)
  1704. * @since 1.5
  1705. */
  1706. public BigDecimal plus(MathContext mc) {
  1707. if (mc.precision == 0) // no rounding please
  1708. return this;
  1709. BigDecimal rhs = this;
  1710. return rhs.doRound(mc);
  1711. }
  1712. /**
  1713. * Returns the signum function of this <tt>BigDecimal</tt>.
  1714. *
  1715. * @return -1, 0, or 1 as the value of this <tt>BigDecimal</tt>
  1716. * is negative, zero, or positive.
  1717. */
  1718. public int signum() {
  1719. return intVal.signum();
  1720. }
  1721. /**
  1722. * Returns the <i>scale</i> of this <tt>BigDecimal</tt>. If zero
  1723. * or positive, the scale is the number of digits to the right of
  1724. * the decimal point. If negative, the unscaled value of the
  1725. * number is multiplied by ten to the power of the negation of the
  1726. * scale. For example, a scale of <tt>-3</tt> means the unscaled
  1727. * value is multiplied by 1000.
  1728. *
  1729. * @return the scale of this <tt>BigDecimal</tt>.
  1730. */
  1731. public int scale() {
  1732. return scale;
  1733. }
  1734. /**
  1735. * Returns the <i>precision</i> of this <tt>BigDecimal</tt>. (The
  1736. * precision is the number of digits in the unscaled value.)
  1737. *
  1738. * <p>The precision of a zero value is 1.
  1739. *
  1740. * @return the precision of this <tt>BigDecimal</tt>.
  1741. * @since 1.5
  1742. */
  1743. public int precision() {
  1744. int result = precision;
  1745. if (result == 0) {
  1746. result = digitLength();
  1747. precision = result;
  1748. }
  1749. return result;
  1750. }
  1751. /**
  1752. * Returns a <tt>BigInteger</tt> whose value is the <i>unscaled
  1753. * value</i> of this <tt>BigDecimal</tt>. (Computes <tt>(this *
  1754. * 10<sup>this.scale()</sup>)</tt>.)
  1755. *
  1756. * @return the unscaled value of this <tt>BigDecimal</tt>.
  1757. * @since 1.2
  1758. */
  1759. public BigInteger unscaledValue() {
  1760. return intVal;
  1761. }
  1762. // Rounding Modes
  1763. /**
  1764. * Rounding mode to round away from zero. Always increments the
  1765. * digit prior to a nonzero discarded fraction. Note that this rounding
  1766. * mode never decreases the magnitude of the calculated value.
  1767. */
  1768. public final static int ROUND_UP = 0;
  1769. /**
  1770. * Rounding mode to round towards zero. Never increments the digit
  1771. * prior to a discarded fraction (i.e., truncates). Note that this
  1772. * rounding mode never increases the magnitude of the calculated value.
  1773. */
  1774. public final static int ROUND_DOWN = 1;
  1775. /**
  1776. * Rounding mode to round towards positive infinity. If the
  1777. * <tt>BigDecimal</tt> is positive, behaves as for
  1778. * <tt>ROUND_UP</tt> if negative, behaves as for
  1779. * <tt>ROUND_DOWN</tt>. Note that this rounding mode never
  1780. * decreases the calculated value.
  1781. */
  1782. public final static int ROUND_CEILING = 2;
  1783. /**
  1784. * Rounding mode to round towards negative infinity. If the
  1785. * <tt>BigDecimal</tt> is positive, behave as for
  1786. * <tt>ROUND_DOWN</tt> if negative, behave as for
  1787. * <tt>ROUND_UP</tt>. Note that this rounding mode never
  1788. * increases the calculated value.
  1789. */
  1790. public final static int ROUND_FLOOR = 3;
  1791. /**
  1792. * Rounding mode to round towards "nearest neighbor"
  1793. * unless both neighbors are equidistant, in which case round up.
  1794. * Behaves as for <tt>ROUND_UP</tt> if the discarded fraction is
  1795. * >= 0.5; otherwise, behaves as for <tt>ROUND_DOWN</tt>. Note
  1796. * that this is the rounding mode that most of us were taught in
  1797. * grade school.
  1798. */
  1799. public final static int ROUND_HALF_UP = 4;
  1800. /**
  1801. * Rounding mode to round towards "nearest neighbor"
  1802. * unless both neighbors are equidistant, in which case round
  1803. * down. Behaves as for <tt>ROUND_UP</tt> if the discarded
  1804. * fraction is > 0.5; otherwise, behaves as for
  1805. * <tt>ROUND_DOWN</tt>.
  1806. */
  1807. public final static int ROUND_HALF_DOWN = 5;
  1808. /**
  1809. * Rounding mode to round towards the "nearest neighbor"
  1810. * unless both neighbors are equidistant, in which case, round
  1811. * towards the even neighbor. Behaves as for
  1812. * <tt>ROUND_HALF_UP</tt> if the digit to the left of the
  1813. * discarded fraction is odd; behaves as for
  1814. * <tt>ROUND_HALF_DOWN</tt> if it's even. Note that this is the
  1815. * rounding mode that minimizes cumulative error when applied
  1816. * repeatedly over a sequence of calculations.
  1817. */
  1818. public final static int ROUND_HALF_EVEN = 6;
  1819. /**
  1820. * Rounding mode to assert that the requested operation has an exact
  1821. * result, hence no rounding is necessary. If this rounding mode is
  1822. * specified on an operation that yields an inexact result, an
  1823. * <tt>ArithmeticException</tt> is thrown.
  1824. */
  1825. public final static int ROUND_UNNECESSARY = 7;
  1826. // Scaling/Rounding Operations
  1827. /**
  1828. * Returns a <tt>BigDecimal</tt> rounded according to the
  1829. * <tt>MathContext</tt> settings. If the precision setting is 0 then
  1830. * no rounding takes place.
  1831. *
  1832. * <p>The effect of this method is identical to that of the
  1833. * {@link #plus(MathContext)} method.
  1834. *
  1835. * @param mc the context to use.
  1836. * @return a <tt>BigDecimal</tt> rounded according to the
  1837. * <tt>MathContext</tt> settings.
  1838. * @throws ArithmeticException if the rounding mode is
  1839. * <tt>UNNECESSARY</tt> and the
  1840. * <tt>BigDecimal</tt> operation would require rounding.
  1841. * @see #plus(MathContext)
  1842. * @since 1.5
  1843. */
  1844. public BigDecimal round(MathContext mc) {
  1845. return plus(mc);
  1846. }
  1847. /**
  1848. * Returns a <tt>BigDecimal</tt> whose scale is the specified
  1849. * value, and whose unscaled value is determined by multiplying or
  1850. * dividing this <tt>BigDecimal</tt>'s unscaled value by the
  1851. * appropriate power of ten to maintain its overall value. If the
  1852. * scale is reduced by the operation, the unscaled value must be
  1853. * divided (rather than multiplied), and the value may be changed;
  1854. * in this case, the specified rounding mode is applied to the
  1855. * division.
  1856. *
  1857. * @param newScale scale of the <tt>BigDecimal</tt> value to be returned.
  1858. * @param roundingMode The rounding mode to apply.
  1859. * @return a <tt>BigDecimal</tt> whose scale is the specified value,
  1860. * and whose unscaled value is determined by multiplying or
  1861. * dividing this <tt>BigDecimal</tt>'s unscaled value by the
  1862. * appropriate power of ten to maintain its overall value.
  1863. * @throws ArithmeticException if <tt>roundingMode==UNNECESSARY</tt>
  1864. * and the specified scaling operation would require
  1865. * rounding.
  1866. * @see RoundingMode
  1867. * @since 1.5
  1868. */
  1869. public BigDecimal setScale(int newScale, RoundingMode roundingMode) {
  1870. return setScale(newScale, roundingMode.oldMode);
  1871. }
  1872. /**
  1873. * Returns a <tt>BigDecimal</tt> whose scale is the specified
  1874. * value, and whose unscaled value is determined by multiplying or
  1875. * dividing this <tt>BigDecimal</tt>'s unscaled value by the
  1876. * appropriate power of ten to maintain its overall value. If the
  1877. * scale is reduced by the operation, the unscaled value must be
  1878. * divided (rather than multiplied), and the value may be changed;
  1879. * in this case, the specified rounding mode is applied to the
  1880. * division.
  1881. *
  1882. * <p>Note that since BigDecimal objects are immutable, calls of
  1883. * this method do <i>not</i> result in the original object being
  1884. * modified, contrary to the usual convention of having methods
  1885. * named <tt>set<i>X</i></tt> mutate field <tt><i>X</i></tt>.
  1886. * Instead, <tt>setScale</tt> returns an object with the proper
  1887. * scale; the returned object may or may not be newly allocated.
  1888. *
  1889. * <p>The new {@link #setScale(int, RoundingMode)} method should
  1890. * be used in preference to this legacy method.
  1891. *
  1892. * @param newScale scale of the <tt>BigDecimal</tt> value to be returned.
  1893. * @param roundingMode The rounding mode to apply.
  1894. * @return a <tt>BigDecimal</tt> whose scale is the specified value,
  1895. * and whose unscaled value is determined by multiplying or
  1896. * dividing this <tt>BigDecimal</tt>'s unscaled value by the
  1897. * appropriate power of ten to maintain its overall value.
  1898. * @throws ArithmeticException if <tt>roundingMode==ROUND_UNNECESSARY</tt>
  1899. * and the specified scaling operation would require
  1900. * rounding.
  1901. * @throws IllegalArgumentException if <tt>roundingMode</tt> does not
  1902. * represent a valid rounding mode.
  1903. * @see #ROUND_UP
  1904. * @see #ROUND_DOWN
  1905. * @see #ROUND_CEILING
  1906. * @see #ROUND_FLOOR
  1907. * @see #ROUND_HALF_UP
  1908. * @see #ROUND_HALF_DOWN
  1909. * @see #ROUND_HALF_EVEN
  1910. * @see #ROUND_UNNECESSARY
  1911. */
  1912. public BigDecimal setScale(int newScale, int roundingMode) {
  1913. if (roundingMode < ROUND_UP || roundingMode > ROUND_UNNECESSARY)
  1914. throw new IllegalArgumentException("Invalid rounding mode");
  1915. if (newScale == this.scale) // easy case
  1916. return this;
  1917. if (this.signum() == 0) // zero can have any scale
  1918. return new BigDecimal(BigInteger.ZERO, newScale);
  1919. if (newScale > this.scale) {
  1920. // [we can use checkScale to assure multiplier is valid]
  1921. int raise = checkScale((long)newScale - this.scale);
  1922. BigDecimal result = new BigDecimal(
  1923. intVal.multiply(tenToThe(raise)), newScale);
  1924. if (this.precision > 0)
  1925. result.precision = this.precision + newScale - this.scale;
  1926. return result;
  1927. }
  1928. /* scale < this.scale */
  1929. // we cannot perfectly predict the precision after rounding
  1930. return divide(ONE, newScale, roundingMode);
  1931. }
  1932. /**
  1933. * Returns a <tt>BigDecimal</tt> whose scale is the specified
  1934. * value, and whose value is numerically equal to this
  1935. * <tt>BigDecimal</tt>'s. Throws an <tt>ArithmeticException</tt>
  1936. * if this is not possible.
  1937. *
  1938. * <p>This call is typically used to increase the scale, in which
  1939. * case it is guaranteed that there exists a <tt>BigDecimal</tt>
  1940. * of the specified scale and the correct value. The call can
  1941. * also be used to reduce the scale if the caller knows that the
  1942. * <tt>BigDecimal</tt> has sufficiently many zeros at the end of
  1943. * its fractional part (i.e., factors of ten in its integer value)
  1944. * to allow for the rescaling without changing its value.
  1945. *
  1946. * <p>This method returns the same result as the two-argument
  1947. * versions of <tt>setScale</tt>, but saves the caller the trouble
  1948. * of specifying a rounding mode in cases where it is irrelevant.
  1949. *
  1950. * <p>Note that since <tt>BigDecimal</tt> objects are immutable,
  1951. * calls of this method do <i>not</i> result in the original
  1952. * object being modified, contrary to the usual convention of
  1953. * having methods named <tt>set<i>X</i></tt> mutate field
  1954. * <tt><i>X</i></tt>. Instead, <tt>setScale</tt> returns an
  1955. * object with the proper scale; the returned object may or may
  1956. * not be newly allocated.
  1957. *
  1958. * @param newScale scale of the <tt>BigDecimal</tt> value to be returned.
  1959. * @return a <tt>BigDecimal</tt> whose scale is the specified value, and
  1960. * whose unscaled value is determined by multiplying or dividing
  1961. * this <tt>BigDecimal</tt>'s unscaled value by the appropriate
  1962. * power of ten to maintain its overall value.
  1963. * @throws ArithmeticException if the specified scaling operation would
  1964. * require rounding.
  1965. * @see #setScale(int, int)
  1966. * @see #setScale(int, RoundingMode)
  1967. */
  1968. public BigDecimal setScale(int newScale) {
  1969. return setScale(newScale, ROUND_UNNECESSARY);
  1970. }
  1971. // Decimal Point Motion Operations
  1972. /**
  1973. * Returns a <tt>BigDecimal</tt> which is equivalent to this one
  1974. * with the decimal point moved <tt>n</tt> places to the left. If
  1975. * <tt>n</tt> is non-negative, the call merely adds <tt>n</tt> to
  1976. * the scale. If <tt>n</tt> is negative, the call is equivalent
  1977. * to <tt>movePointRight(-n)</tt>. The <tt>BigDecimal</tt>
  1978. * returned by this call has value <tt>(this ×
  1979. * 10<sup>-n</sup>)</tt> and scale <tt>max(this.scale()+n,
  1980. * 0)</tt>.
  1981. *
  1982. * @param n number of places to move the decimal point to the left.
  1983. * @return a <tt>BigDecimal</tt> which is equivalent to this one with the
  1984. * decimal point moved <tt>n</tt> places to the left.
  1985. * @throws ArithmeticException if scale overflows.
  1986. */
  1987. public BigDecimal movePointLeft(int n) {
  1988. // Cannot use movePointRight(-n) in case of n==Integer.MIN_VALUE
  1989. BigDecimal num = new BigDecimal(intVal, checkScale((long)scale + n));
  1990. return (num.scale<0 ? num.setScale(0) : num);
  1991. }
  1992. /**
  1993. * Returns a <tt>BigDecimal</tt> which is equivalent to this one
  1994. * with the decimal point moved <tt>n</tt> places to the right.
  1995. * If <tt>n</tt> is non-negative, the call merely subtracts
  1996. * <tt>n</tt> from the scale. If <tt>n</tt> is negative, the call
  1997. * is equivalent to <tt>movePointLeft(-n)</tt>. The
  1998. * <tt>BigDecimal</tt> returned by this call has value <tt>(this
  1999. * × 10<sup>n</sup>)</tt> and scale <tt>max(this.scale()-n,
  2000. * 0)</tt>.
  2001. *
  2002. * @param n number of places to move the decimal point to the right.
  2003. * @return a <tt>BigDecimal</tt> which is equivalent to this one
  2004. * with the decimal point moved <tt>n</tt> places to the right.
  2005. * @throws ArithmeticException if scale overflows.
  2006. */
  2007. public BigDecimal movePointRight(int n) {
  2008. // Cannot use movePointLeft(-n) in case of n==Integer.MIN_VALUE
  2009. BigDecimal num = new BigDecimal(intVal, checkScale((long)scale - n));
  2010. return (num.scale<0 ? num.setScale(0) : num);
  2011. }
  2012. /**
  2013. * Returns a BigDecimal whose numerical value is equal to
  2014. * (<tt>this</tt> * 10<sup>n</sup>). The scale of
  2015. * the result is <tt>(this.scale() - n)</tt>.
  2016. *
  2017. * @throws ArithmeticException if the scale would be
  2018. * outside the range of a 32-bit integer.
  2019. *
  2020. * @since 1.5
  2021. */
  2022. public BigDecimal scaleByPowerOfTen(int n) {
  2023. BigDecimal num = new BigDecimal(intVal, checkScale((long)scale - n));
  2024. num.precision = precision;
  2025. return num;
  2026. }
  2027. /**
  2028. * Returns a <tt>BigDecimal</tt> which is numerically equal to
  2029. * this one but with any trailing zeros removed from the
  2030. * representation. For example, stripping the trailing zeros from
  2031. * the <tt>BigDecimal</tt> value <tt>600.0</tt>, which has
  2032. * [<tt>BigInteger</tt>, <tt>scale</tt>] components equals to
  2033. * [6000, 1], yields <tt>6E2</tt> with [<tt>BigInteger</tt>,
  2034. * <tt>scale</tt>] components equals to [6, -2]
  2035. *
  2036. * @return a numerically equal <tt>BigDecimal</tt> with any
  2037. * trailing zeros removed.
  2038. */
  2039. public BigDecimal stripTrailingZeros() {
  2040. return (new BigDecimal(intVal, scale)).stripZerosToMatchScale(Long.MIN_VALUE);
  2041. }
  2042. // Comparison Operations
  2043. /**
  2044. * Compares this <tt>BigDecimal</tt> with the specified
  2045. * <tt>BigDecimal</tt>. Two <tt>BigDecimal</tt> objects that are
  2046. * equal in value but have a different scale (like 2.0 and 2.00)
  2047. * are considered equal by this method. This method is provided
  2048. * in preference to individual methods for each of the six boolean
  2049. * comparison operators (<, ==, >, >=, !=, <=). The
  2050. * suggested idiom for performing these comparisons is:
  2051. * <tt>(x.compareTo(y)</tt> <<i>op</i>> <tt>0)</tt>, where
  2052. * <<i>op</i>> is one of the six comparison operators.
  2053. *
  2054. * @param val <tt>BigDecimal</tt> to which this <tt>BigDecimal</tt> is
  2055. * to be compared.
  2056. * @return -1, 0, or 1 as this <tt>BigDecimal</tt> is numerically
  2057. * less than, equal to, or greater than <tt>val</tt>.
  2058. */
  2059. public int compareTo(BigDecimal val) {
  2060. /* Optimization: would run fine without the next three lines */
  2061. int sigDiff = signum() - val.signum();
  2062. if (sigDiff != 0)
  2063. return (sigDiff > 0 ? 1 : -1);
  2064. // If the (adjusted) exponents are different we do not need to
  2065. // expensively match scales and compare the significands
  2066. int aethis = this.precision() - this.scale; // [-1]
  2067. int aeval = val.precision() - val.scale; // [-1]
  2068. if (aethis < aeval)
  2069. return -this.signum();
  2070. else if (aethis > aeval)
  2071. return this.signum();
  2072. // Scale and compare intVals
  2073. BigDecimal arg[] = new BigDecimal[2];
  2074. arg[0] = this; arg[1] = val;
  2075. matchScale(arg);
  2076. return arg[0].intVal.compareTo(arg[1].intVal);
  2077. }
  2078. /**
  2079. * Compares this <tt>BigDecimal</tt> with the specified
  2080. * <tt>Object</tt> for equality. Unlike {@link
  2081. * #compareTo(BigDecimal) compareTo}, this method considers two
  2082. * <tt>BigDecimal</tt> objects equal only if they are equal in
  2083. * value and scale (thus 2.0 is not equal to 2.00 when compared by
  2084. * this method).
  2085. *
  2086. * @param x <tt>Object</tt> to which this <tt>BigDecimal</tt> is
  2087. * to be compared.
  2088. * @return <tt>true</tt> if and only if the specified <tt>Object</tt> is a
  2089. * <tt>BigDecimal</tt> whose value and scale are equal to this
  2090. * <tt>BigDecimal</tt>'s.
  2091. * @see #compareTo(java.math.BigDecimal)
  2092. * @see #hashCode
  2093. */
  2094. public boolean equals(Object x) {
  2095. if (!(x instanceof BigDecimal))
  2096. return false;
  2097. BigDecimal xDec = (BigDecimal) x;
  2098. return scale == xDec.scale && intVal.equals(xDec.intVal);
  2099. }
  2100. /**
  2101. * Returns the minimum of this <tt>BigDecimal</tt> and
  2102. * <tt>val</tt>.
  2103. *
  2104. * @param val value with which the minimum is to be computed.
  2105. * @return the <tt>BigDecimal</tt> whose value is the lesser of this
  2106. * <tt>BigDecimal</tt> and <tt>val</tt>. If they are equal,
  2107. * as defined by the {@link #compareTo(BigDecimal) compareTo}
  2108. * method, <tt>this</tt> is returned.
  2109. * @see #compareTo(java.math.BigDecimal)
  2110. */
  2111. public BigDecimal min(BigDecimal val) {
  2112. return (compareTo(val) <= 0 ? this : val);
  2113. }
  2114. /**
  2115. * Returns the maximum of this <tt>BigDecimal</tt> and <tt>val</tt>.
  2116. *
  2117. * @param val value with which the maximum is to be computed.
  2118. * @return the <tt>BigDecimal</tt> whose value is the greater of this
  2119. * <tt>BigDecimal</tt> and <tt>val</tt>. If they are equal,
  2120. * as defined by the {@link #compareTo(BigDecimal) compareTo}
  2121. * method, <tt>this</tt> is returned.
  2122. * @see #compareTo(java.math.BigDecimal)
  2123. */
  2124. public BigDecimal max(BigDecimal val) {
  2125. return (compareTo(val) >= 0 ? this : val);
  2126. }
  2127. // Hash Function
  2128. /**
  2129. * Returns the hash code for this <tt>BigDecimal</tt>. Note that
  2130. * two <tt>BigDecimal</tt> objects that are numerically equal but
  2131. * differ in scale (like 2.0 and 2.00) will generally <i>not</i>
  2132. * have the same hash code.
  2133. *
  2134. * @return hash code for this <tt>BigDecimal</tt>.
  2135. * @see #equals(Object)
  2136. */
  2137. public int hashCode() {
  2138. return 31*intVal.hashCode() + scale;
  2139. }
  2140. // Format Converters
  2141. /**
  2142. * Returns the string representation of this <tt>BigDecimal</tt>,
  2143. * using scientific notation if an exponent is needed.
  2144. *
  2145. * <p>A standard canonical string form of the <tt>BigDecimal</tt>
  2146. * is created as though by the following steps: first, the
  2147. * absolute value of the unscaled value of the <tt>BigDecimal</tt>
  2148. * is converted to a string in base ten using the characters
  2149. * <tt>'0'</tt> through <tt>'9'</tt> with no leading zeros (except
  2150. * if its value is zero, in which case a single <tt>'0'</tt>
  2151. * character is used).
  2152. *
  2153. * <p>Next, an <i>adjusted exponent</i> is calculated; this is the
  2154. * negated scale, plus the number of characters in the converted
  2155. * unscaled value, less one. That is,
  2156. * <tt>-scale+(ulength-1)</tt>, where <tt>ulength</tt> is the
  2157. * length of the absolute value of the unscaled value in decimal
  2158. * digits (its <i>precision</i>).
  2159. *
  2160. * <p>If the scale is greater than or equal to zero and the
  2161. * adjusted exponent is greater than or equal to <tt>-6</tt>, the
  2162. * number will be converted to a character form without using
  2163. * exponential notation. In this case, if the scale is zero then
  2164. * no decimal point is added and if the scale is positive a
  2165. * decimal point will be inserted with the scale specifying the
  2166. * number of characters to the right of the decimal point.
  2167. * <tt>'0'</tt> characters are added to the left of the converted
  2168. * unscaled value as necessary. If no character precedes the
  2169. * decimal point after this insertion then a conventional
  2170. * <tt>'0'</tt> character is prefixed.
  2171. *
  2172. * <p>Otherwise (that is, if the scale is negative, or the
  2173. * adjusted exponent is less than <tt>-6</tt>), the number will be
  2174. * converted to a character form using exponential notation. In
  2175. * this case, if the converted <tt>BigInteger</tt> has more than
  2176. * one digit a decimal point is inserted after the first digit.
  2177. * An exponent in character form is then suffixed to the converted
  2178. * unscaled value (perhaps with inserted decimal point); this
  2179. * comprises the letter <tt>'E'</tt> followed immediately by the
  2180. * adjusted exponent converted to a character form. The latter is
  2181. * in base ten, using the characters <tt>'0'</tt> through
  2182. * <tt>'9'</tt> with no leading zeros, and is always prefixed by a
  2183. * sign character <tt>'-'</tt> (<tt>'\u002D'</tt>) if the
  2184. * adjusted exponent is negative, <tt>'+'</tt>
  2185. * (<tt>'\u002B'</tt>) otherwise).
  2186. *
  2187. * <p>Finally, the entire string is prefixed by a minus sign
  2188. * character <tt>'-'</tt> (<tt>'\u002D'</tt>) if the unscaled
  2189. * value is less than zero. No sign character is prefixed if the
  2190. * unscaled value is zero or positive.
  2191. *
  2192. * <p><b>Examples:</b>
  2193. * <p>For each representation [<i>unscaled value</i>, <i>scale</i>]
  2194. * on the left, the resulting string is shown on the right.
  2195. * <pre>
  2196. * [123,0] "123"
  2197. * [-123,0] "-123"
  2198. * [123,-1] "1.23E+3"
  2199. * [123,-3] "1.23E+5"
  2200. * [123,1] "12.3"
  2201. * [123,5] "0.00123"
  2202. * [123,10] "1.23E-8"
  2203. * [-123,12] "-1.23E-10"
  2204. * </pre>
  2205. *
  2206. * <b>Notes:</b>
  2207. * <ol>
  2208. *
  2209. * <li>There is a one-to-one mapping between the distinguishable
  2210. * <tt>BigDecimal</tt> values and the result of this conversion.
  2211. * That is, every distinguishable <tt>BigDecimal</tt> value
  2212. * (unscaled value and scale) has a unique string representation
  2213. * as a result of using <tt>toString</tt>. If that string
  2214. * representation is converted back to a <tt>BigDecimal</tt> using
  2215. * the {@link #BigDecimal(String)} constructor, then the original
  2216. * value will be recovered.
  2217. *
  2218. * <li>The string produced for a given number is always the same;
  2219. * it is not affected by locale. This means that it can be used
  2220. * as a canonical string representation for exchanging decimal
  2221. * data, or as a key for a Hashtable, etc. Locale-sensitive
  2222. * number formatting and parsing is handled by the {@link
  2223. * java.text.NumberFormat} class and its subclasses.
  2224. *
  2225. * <li>The {@link #toEngineeringString} method may be used for
  2226. * presenting numbers with exponents in engineering notation, and the
  2227. * {@link #setScale(int,RoundingMode) setScale} method may be used for
  2228. * rounding a <tt>BigDecimal</tt> so it has a known number of digits after
  2229. * the decimal point.
  2230. *
  2231. * <li>The digit-to-character mapping provided by
  2232. * <tt>Character.forDigit</tt> is used.
  2233. *
  2234. * </ol>
  2235. *
  2236. * @return string representation of this <tt>BigDecimal</tt>.
  2237. * @see Character#forDigit
  2238. * @see #BigDecimal(java.lang.String)
  2239. */
  2240. public String toString() {
  2241. return new String(layoutChars(true));
  2242. }
  2243. /**
  2244. * Returns a string representation of this <tt>BigDecimal</tt>,
  2245. * using engineering notation if an exponent is needed.
  2246. *
  2247. * <p>Returns a string that represents the <tt>BigDecimal</tt> as
  2248. * described in the {@link #toString()} method, except that if
  2249. * exponential notation is used, the power of ten is adjusted to
  2250. * be a multiple of three (engineering notation) such that the
  2251. * integer part of nonzero values will be in the range 1 through
  2252. * 999. If exponential notation is used for zero values, a
  2253. * decimal point and one or two fractional zero digits are used so
  2254. * that the scale of the zero value is preserved. Note that
  2255. * unlike the output of {@link #toString()}, the output of this
  2256. * method is <em>not</em> guaranteed to recover the same [integer,
  2257. * scale] pair of this <tt>BigDecimal</tt> if the output string is
  2258. * converting back to a <tt>BigDecimal</tt> using the {@linkplain
  2259. * #BigDecimal(String) string constructor}. The result of this method meets
  2260. * the weaker constraint of always producing a numerically equal
  2261. * result from applying the string constructor to the method's output.
  2262. *
  2263. * @return string representation of this <tt>BigDecimal</tt>, using
  2264. * engineering notation if an exponent is needed.
  2265. * @since 1.5
  2266. */
  2267. public String toEngineeringString() {
  2268. return new String(layoutChars(false));
  2269. }
  2270. /**
  2271. * Returns a string representation of this <tt>BigDecimal</tt>
  2272. * without an exponent field. For values with a positive scale,
  2273. * the number of digits to the right of the decimal point is used
  2274. * to indicate scale. For values with a zero or negative scale,
  2275. * the resulting string is generated as if the value were
  2276. * converted to a numerically equal value with zero scale and as
  2277. * if all the trailing zeros of the zero scale value were present
  2278. * in the result.
  2279. *
  2280. * The entire string is prefixed by a minus sign character '-'
  2281. * (<tt>'\u002D'</tt>) if the unscaled value is less than
  2282. * zero. No sign character is prefixed if the unscaled value is
  2283. * zero or positive.
  2284. *
  2285. * Note that if the result of this method is passed to the
  2286. * {@linkplain #BigDecimal(String) string constructor}, only the
  2287. * numerical value of this <tt>BigDecimal</tt> will necessarily be
  2288. * recovered; the representation of the new <tt>BigDecimal</tt>
  2289. * may have a different scale. In particular, if this
  2290. * <tt>BigDecimal</tt> has a positive scale, the string resulting
  2291. * from this method will have a scale of zero when processed by
  2292. * the string constructor.
  2293. *
  2294. * (This method behaves analogously to the <tt>toString</tt>
  2295. * method in 1.4 and earlier releases.)
  2296. *
  2297. * @return a string representation of this <tt>BigDecimal</tt>
  2298. * without an exponent field.
  2299. * @since 1.5
  2300. * @see #toString()
  2301. * @see #toEngineeringString()
  2302. */
  2303. public String toPlainString() {
  2304. BigDecimal bd = this;
  2305. if (bd.scale < 0)
  2306. bd = bd.setScale(0);
  2307. if (bd.scale == 0) /* No decimal point */
  2308. return bd.intVal.toString();
  2309. return bd.getValueString(bd.signum(), bd.intVal.abs().toString(), bd.scale);
  2310. }
  2311. /* Returns a digit.digit string */
  2312. private String getValueString(int signum, String intString, int scale) {
  2313. /* Insert decimal point */
  2314. StringBuilder buf;
  2315. int insertionPoint = intString.length() - scale;
  2316. if (insertionPoint == 0) { /* Point goes right before intVal */
  2317. return (signum<0 ? "-0." : "0.") + intString;
  2318. } else if (insertionPoint > 0) { /* Point goes inside intVal */
  2319. buf = new StringBuilder(intString);
  2320. buf.insert(insertionPoint, '.');
  2321. if (signum < 0)
  2322. buf.insert(0, '-');
  2323. } else { /* We must insert zeros between point and intVal */
  2324. buf = new StringBuilder(3-insertionPoint + intString.length());
  2325. buf.append(signum<0 ? "-0." : "0.");
  2326. for (int i=0; i<-insertionPoint; i++)
  2327. buf.append('0');
  2328. buf.append(intString);
  2329. }
  2330. return buf.toString();
  2331. }
  2332. /**
  2333. * Returns the string representation of this <tt>BigDecimal</tt>,
  2334. * as a character array. This returns a character array that has
  2335. * the same content as a call to {@link #toString()} followed by a
  2336. * call to {@link String#toCharArray()}, but without the overhead
  2337. * of creating the intermediate <tt>String</tt> object.
  2338. *
  2339. * @return <tt>char[]</tt> representation of this <tt>BigDecimal</tt>.
  2340. * @see #toString()
  2341. * @since 1.5
  2342. */
  2343. char[] toCharArray() { // for use within java.math only
  2344. return layoutChars(true);
  2345. }
  2346. /**
  2347. * Converts this <tt>BigDecimal</tt> to a <tt>BigInteger</tt>.
  2348. * This conversion is analogous to a <a
  2349. * href="http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363"><i>narrowing
  2350. * primitive conversion</i></a> from <tt>double</tt> to
  2351. * <tt>long</tt> as defined in the <a
  2352. * href="http://java.sun.com/docs/books/jls/html/">Java Language
  2353. * Specification</a>: any fractional part of this
  2354. * <tt>BigDecimal</tt> will be discarded. Note that this
  2355. * conversion can lose information about the precision of the
  2356. * <tt>BigDecimal</tt> value.
  2357. * <p>
  2358. * To have an exception thrown if the conversion is inexact (in
  2359. * other words if a nonzero fractional part is discarded), use the
  2360. * {@link #toBigIntegerExact()} method.
  2361. *
  2362. * @return this <tt>BigDecimal</tt> converted to a <tt>BigInteger</tt>.
  2363. */
  2364. public BigInteger toBigInteger() {
  2365. // force to an integer, quietly
  2366. return this.setScale(0, ROUND_DOWN).intVal;
  2367. }
  2368. /**
  2369. * Converts this <tt>BigDecimal</tt> to a <tt>BigInteger</tt>,
  2370. * checking for lost information. An exception is thrown if this
  2371. * <tt>BigDecimal</tt> has a nonzero fractional part.
  2372. *
  2373. * @return this <tt>BigDecimal</tt> converted to a <tt>BigInteger</tt>.
  2374. * @throws ArithmeticException if <tt>this</tt> has a nonzero
  2375. * fractional part.
  2376. * @since 1.5
  2377. */
  2378. public BigInteger toBigIntegerExact() {
  2379. // round to an integer, with Exception if decimal part non-0
  2380. return this.setScale(0, ROUND_UNNECESSARY).intVal;
  2381. }
  2382. /**
  2383. * Converts this <tt>BigDecimal</tt> to a <tt>long</tt>. This
  2384. * conversion is analogous to a <a
  2385. * href="http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363"><i>narrowing
  2386. * primitive conversion</i></a> from <tt>double</tt> to
  2387. * <tt>short</tt> as defined in the <a
  2388. * href="http://java.sun.com/docs/books/jls/html/">Java Language
  2389. * Specification</a>: any fractional part of this
  2390. * <tt>BigDecimal</tt> will be discarded, and if the resulting
  2391. * "<tt>BigInteger</tt>" is too big to fit in a
  2392. * <tt>long</tt>, only the low-order 64 bits are returned.
  2393. * Note that this conversion can lose information about the
  2394. * overall magnitude and precision of this <tt>BigDecimal</tt> value as well
  2395. * as return a result with the opposite sign.
  2396. *
  2397. * @return this <tt>BigDecimal</tt> converted to an <tt>long</tt>.
  2398. */
  2399. public long longValue(){
  2400. return toBigInteger().longValue();
  2401. }
  2402. /**
  2403. * Converts this <tt>BigDecimal</tt> to a <tt>long</tt>, checking
  2404. * for lost information. If this <tt>BigDecimal</tt> has a
  2405. * nonzero fractional part or is out of the possible range for a
  2406. * <tt>long</tt> result then an <tt>ArithmeticException</tt> is
  2407. * thrown.
  2408. *
  2409. * @return this <tt>BigDecimal</tt> converted to a <tt>long</tt>.
  2410. * @throws ArithmeticException if <tt>this</tt> has a nonzero
  2411. * fractional part, or will not fit in a <tt>long</tt>.
  2412. * @since 1.5
  2413. */
  2414. public long longValueExact() {
  2415. // If more than 19 digits in integer part it cannot possibly fit
  2416. if ((precision() - scale) > 19) // [OK for neagtive scale too]
  2417. throw new java.lang.ArithmeticException("Overflow");
  2418. // Fastpath zero and < 1.0 numbers (the latter can be very slow
  2419. // to round if very small)
  2420. if (this.intVal.signum() == 0)
  2421. return 0;
  2422. if ((this.precision() - this.scale) <= 0)
  2423. throw new ArithmeticException("Rounding necessary");
  2424. // round to an integer, with Exception if decimal part non-0
  2425. BigDecimal num = this.setScale(0, ROUND_UNNECESSARY);
  2426. if (num.precision() >= 19) { // need to check carefully
  2427. if (LONGMIN == null) { // initialize constants
  2428. LONGMIN = BigInteger.valueOf(Long.MIN_VALUE);
  2429. LONGMAX = BigInteger.valueOf(Long.MAX_VALUE);
  2430. }
  2431. if ((num.intVal.compareTo(LONGMIN) < 0) ||
  2432. (num.intVal.compareTo(LONGMAX) > 0))
  2433. throw new java.lang.ArithmeticException("Overflow");
  2434. }
  2435. return num.intVal.longValue();
  2436. }
  2437. // These constants are only initialized if needed
  2438. /** BigInteger equal to Long.MIN_VALUE. */
  2439. private static BigInteger LONGMIN = null;
  2440. /** BigInteger equal to Long.MAX_VALUE. */
  2441. private static BigInteger LONGMAX = null;
  2442. /**
  2443. * Converts this <tt>BigDecimal</tt> to an <tt>int</tt>. This
  2444. * conversion is analogous to a <a
  2445. * href="http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363"><i>narrowing
  2446. * primitive conversion</i></a> from <tt>double</tt> to
  2447. * <tt>short</tt> as defined in the <a
  2448. * href="http://java.sun.com/docs/books/jls/html/">Java Language
  2449. * Specification</a>: any fractional part of this
  2450. * <tt>BigDecimal</tt> will be discarded, and if the resulting
  2451. * "<tt>BigInteger</tt>" is too big to fit in an
  2452. * <tt>int</tt>, only the low-order 32 bits are returned.
  2453. * Note that this conversion can lose information about the
  2454. * overall magnitude and precision of this <tt>BigDecimal</tt>
  2455. * value as well as return a result with the opposite sign.
  2456. *
  2457. * @return this <tt>BigDecimal</tt> converted to an <tt>int</tt>.
  2458. */
  2459. public int intValue() {
  2460. return toBigInteger().intValue();
  2461. }
  2462. /**
  2463. * Converts this <tt>BigDecimal</tt> to an <tt>int</tt>, checking
  2464. * for lost information. If this <tt>BigDecimal</tt> has a
  2465. * nonzero fractional part or is out of the possible range for an
  2466. * <tt>int</tt> result then an <tt>ArithmeticException</tt> is
  2467. * thrown.
  2468. *
  2469. * @return this <tt>BigDecimal</tt> converted to an <tt>int</tt>.
  2470. * @throws ArithmeticException if <tt>this</tt> has a nonzero
  2471. * fractional part, or will not fit in an <tt>int</tt>.
  2472. * @since 1.5
  2473. */
  2474. public int intValueExact() {
  2475. long num;
  2476. num = this.longValueExact(); // will check decimal part
  2477. if ((int)num != num)
  2478. throw new java.lang.ArithmeticException("Overflow");
  2479. return (int)num;
  2480. }
  2481. /**
  2482. * Converts this <tt>BigDecimal</tt> to a <tt>short</tt>, checking
  2483. * for lost information. If this <tt>BigDecimal</tt> has a
  2484. * nonzero fractional part or is out of the possible range for a
  2485. * <tt>short</tt> result then an <tt>ArithmeticException</tt> is
  2486. * thrown.
  2487. *
  2488. * @return this <tt>BigDecimal</tt> converted to a <tt>short</tt>.
  2489. * @throws ArithmeticException if <tt>this</tt> has a nonzero
  2490. * fractional part, or will not fit in a <tt>short</tt>.
  2491. * @since 1.5
  2492. */
  2493. public short shortValueExact() {
  2494. long num;
  2495. num = this.longValueExact(); // will check decimal part
  2496. if ((short)num != num)
  2497. throw new java.lang.ArithmeticException("Overflow");
  2498. return (short)num;
  2499. }
  2500. /**
  2501. * Converts this <tt>BigDecimal</tt> to a <tt>byte</tt>, checking
  2502. * for lost information. If this <tt>BigDecimal</tt> has a
  2503. * nonzero fractional part or is out of the possible range for a
  2504. * <tt>byte</tt> result then an <tt>ArithmeticException</tt> is
  2505. * thrown.
  2506. *
  2507. * @return this <tt>BigDecimal</tt> converted to an <tt>byte</tt>.
  2508. * @throws ArithmeticException if <tt>this</tt> has a nonzero
  2509. * fractional part, or will not fit in a <tt>byte</tt>.
  2510. * @since 1.5
  2511. */
  2512. public byte byteValueExact() {
  2513. long num;
  2514. num = this.longValueExact(); // will check decimal part
  2515. if ((byte)num != num)
  2516. throw new java.lang.ArithmeticException("Overflow");
  2517. return (byte)num;
  2518. }
  2519. /**
  2520. * Converts this <tt>BigDecimal</tt> to a <tt>float</tt>.
  2521. * This conversion is similar to the <a
  2522. * href="http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363"><i>narrowing
  2523. * primitive conversion</i></a> from <tt>double</tt> to
  2524. * <tt>float</tt> defined in the <a
  2525. * href="http://java.sun.com/docs/books/jls/html/">Java Language
  2526. * Specification</a>: if this <tt>BigDecimal</tt> has too great a
  2527. * magnitude to represent as a <tt>float</tt>, it will be
  2528. * converted to {@link Float#NEGATIVE_INFINITY} or {@link
  2529. * Float#POSITIVE_INFINITY} as appropriate. Note that even when
  2530. * the return value is finite, this conversion can lose
  2531. * information about the precision of the <tt>BigDecimal</tt>
  2532. * value.
  2533. *
  2534. * @return this <tt>BigDecimal</tt> converted to a <tt>float</tt>.
  2535. */
  2536. public float floatValue(){
  2537. /* Somewhat inefficient, but guaranteed to work. */
  2538. return Float.valueOf(this.toString()).floatValue();
  2539. }
  2540. /**
  2541. * Converts this <tt>BigDecimal</tt> to a <tt>double</tt>.
  2542. * This conversion is similar to the <a
  2543. * href="http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363"><i>narrowing
  2544. * primitive conversion</i></a> from <tt>double</tt> to
  2545. * <tt>float</tt> as defined in the <a
  2546. * href="http://java.sun.com/docs/books/jls/html/">Java Language
  2547. * Specification</a>: if this <tt>BigDecimal</tt> has too great a
  2548. * magnitude represent as a <tt>double</tt>, it will be
  2549. * converted to {@link Double#NEGATIVE_INFINITY} or {@link
  2550. * Double#POSITIVE_INFINITY} as appropriate. Note that even when
  2551. * the return value is finite, this conversion can lose
  2552. * information about the precision of the <tt>BigDecimal</tt>
  2553. * value.
  2554. *
  2555. * @return this <tt>BigDecimal</tt> converted to a <tt>double</tt>.
  2556. */
  2557. public double doubleValue(){
  2558. /* Somewhat inefficient, but guaranteed to work. */
  2559. return Double.valueOf(this.toString()).doubleValue();
  2560. }
  2561. /**
  2562. * Returns the size of an ulp, a unit in the last place, of this
  2563. * <tt>BigDecimal</tt>. An ulp of a nonzero <tt>BigDecimal</tt>
  2564. * value is the positive distance between this value and the
  2565. * <tt>BigDecimal</tt> value next larger in magnitude with the
  2566. * same number of digits. An ulp of a zero value is numerically
  2567. * equal to 1 with the scale of <tt>this</tt>. The result is
  2568. * stored with the same scale as <code>this</code> so the result
  2569. * for zero and nonzero values is equal to <code>[1,
  2570. * this.scale()]</code>.
  2571. *
  2572. * @return the size of an ulp of <tt>this</tt>
  2573. * @since 1.5
  2574. */
  2575. public BigDecimal ulp() {
  2576. return new BigDecimal(BigInteger.ONE, this.scale());
  2577. }
  2578. // Private "Helper" Methods
  2579. /**
  2580. * Lay out this <tt>BigDecimal</tt> into a <tt>char[]</tt> array.
  2581. * The Java 1.2 equivalent to this was called <tt>getValueString</tt>.
  2582. *
  2583. * @param sci <tt>true</tt> for Scientific exponential notation;
  2584. * <tt>false</tt> for Engineering
  2585. * @return <tt>char[]</tt> array with canonical string
  2586. * representation of this <tt>BigDecimal</tt>
  2587. */
  2588. private char[] layoutChars(boolean sci) {
  2589. if (scale == 0) // zero scale is trivial
  2590. return intVal.toString().toCharArray();
  2591. // get the significand as an absolute value
  2592. char coeff[] = intVal.abs().toString().toCharArray();
  2593. // Construct a buffer, with sufficient capacity for all cases.
  2594. // If E-notation is needed, length will be: +1 if negative, +1
  2595. // if '.' needed, +2 for "E+", + up to 10 for adjusted exponent.
  2596. // Otherwise it could have +1 if negative, plus leading "0.00000"
  2597. StringBuilder buf=new StringBuilder(coeff.length+14);
  2598. if (intVal.signum() < 0) // prefix '-' if negative
  2599. buf.append('-');
  2600. long adjusted = -(long)scale + (coeff.length-1);
  2601. if ((scale >= 0) && (adjusted >= -6)) { // plain number
  2602. int pad = scale - coeff.length; // count of padding zeros
  2603. if (pad >= 0) { // 0.xxx form
  2604. buf.append('0');
  2605. buf.append('.');
  2606. for (; pad>0; pad--) {
  2607. buf.append('0');
  2608. }
  2609. buf.append(coeff);
  2610. } else { // xx.xx form
  2611. buf.append(coeff, 0, -pad);
  2612. buf.append('.');
  2613. buf.append(coeff, -pad, scale);
  2614. }
  2615. } else { // E-notation is needed
  2616. if (sci) { // Scientific notation
  2617. buf.append(coeff[0]); // first character
  2618. if (coeff.length > 1) { // more to come
  2619. buf.append('.');
  2620. buf.append(coeff, 1, coeff.length-1);
  2621. }
  2622. } else { // Engineering notation
  2623. int sig = (int)(adjusted % 3);
  2624. if (sig < 0)
  2625. sig += 3; // [adjusted was negative]
  2626. adjusted -= sig; // now a multiple of 3
  2627. sig++;
  2628. if (intVal.signum() == 0) {
  2629. switch (sig) {
  2630. case 1:
  2631. buf.append('0'); // exponent is a multiple of three
  2632. break;
  2633. case 2:
  2634. buf.append("0.00");
  2635. adjusted += 3;
  2636. break;
  2637. case 3:
  2638. buf.append("0.0");
  2639. adjusted += 3;
  2640. break;
  2641. default:
  2642. throw new AssertionError("Unexpected sig value " + sig);
  2643. }
  2644. } else if (sig >= coeff.length) { // significand all in integer
  2645. buf.append(coeff, 0, coeff.length);
  2646. // may need some zeros, too
  2647. for (int i = sig - coeff.length; i > 0; i--)
  2648. buf.append('0');
  2649. } else { // xx.xxE form
  2650. buf.append(coeff, 0, sig);
  2651. buf.append('.');
  2652. buf.append(coeff, sig, coeff.length-sig);
  2653. }
  2654. }
  2655. if (adjusted != 0) { // [!sci could have made 0]
  2656. buf.append('E');
  2657. if (adjusted > 0) // force sign for positive
  2658. buf.append('+');
  2659. buf.append(adjusted);
  2660. }
  2661. }
  2662. char result[] = new char[buf.length()];
  2663. buf.getChars(0, result.length, result, 0);
  2664. return result;
  2665. }
  2666. /**
  2667. * Return 10 to the power n, as a <tt>BigInteger</tt>.
  2668. *
  2669. * @param n the power of ten to be returned (>=0)
  2670. * @return a <tt>BigInteger</tt> with the value (10<sup>n</sup>)
  2671. */
  2672. private static BigInteger tenToThe(int n) {
  2673. if (n < TENPOWERS.length) // use value from constant array
  2674. return TENPOWERS[n];
  2675. // BigInteger.pow is slow, so make 10**n by constructing a
  2676. // BigInteger from a character string (still not very fast)
  2677. char tenpow[] = new char[n + 1];
  2678. tenpow[0] = '1';
  2679. for (int i = 1; i <= n; i++) tenpow[i] = '0';
  2680. return new BigInteger(tenpow);
  2681. }
  2682. private static BigInteger TENPOWERS[] = {BigInteger.ONE,
  2683. BigInteger.valueOf(10), BigInteger.valueOf(100),
  2684. BigInteger.valueOf(1000), BigInteger.valueOf(10000),
  2685. BigInteger.valueOf(100000), BigInteger.valueOf(1000000),
  2686. BigInteger.valueOf(10000000), BigInteger.valueOf(100000000),
  2687. BigInteger.valueOf(1000000000)};
  2688. /**
  2689. * Match the scales of two <tt>BigDecimal<tt>s to align their
  2690. * least significant digits.
  2691. *
  2692. * <p>If the scales of val[0] and val[1] differ, rescale
  2693. * (non-destructively) the lower-scaled <tt>BigDecimal</tt> so
  2694. * they match. That is, the lower-scaled reference will be
  2695. * replaced by a reference to a new object with the same scale as
  2696. * the other <tt>BigDecimal</tt>.
  2697. *
  2698. * @param val array of two elements referring to the two
  2699. * <tt>BigDecimal</tt>s to be aligned.
  2700. */
  2701. private static void matchScale(BigDecimal[] val) {
  2702. if (val[0].scale < val[1].scale)
  2703. val[0] = val[0].setScale(val[1].scale);
  2704. else if (val[1].scale < val[0].scale)
  2705. val[1] = val[1].setScale(val[0].scale);
  2706. }
  2707. /**
  2708. * Reconstitute the <tt>BigDecimal</tt> instance from a stream (that is,
  2709. * deserialize it).
  2710. *
  2711. * @param s the stream being read.
  2712. */
  2713. private synchronized void readObject(java.io.ObjectInputStream s)
  2714. throws java.io.IOException, ClassNotFoundException {
  2715. // Read in all fields
  2716. s.defaultReadObject();
  2717. // validate possibly bad fields
  2718. if (intVal == null) {
  2719. String message = "BigDecimal: null intVal in stream";
  2720. throw new java.io.StreamCorruptedException(message);
  2721. // [all values of scale are now allowed]
  2722. }
  2723. }
  2724. /**
  2725. * Returns the length of this <tt>BigDecimal</tt>, in decimal digits.
  2726. *
  2727. * Notes:
  2728. *<ul>
  2729. * <li> This is performance-critical; most operations where a
  2730. * context is supplied will need at least one call to this
  2731. * method.
  2732. *
  2733. * <li> This should be a method on BigInteger; the call to this
  2734. * method in precision() can then be replaced with the
  2735. * term: intVal.digitLength(). It could also be called
  2736. * precision() in BigInteger.
  2737. *
  2738. * Better still -- the precision lookaside could be moved to
  2739. * BigInteger, too.
  2740. *
  2741. * <li> This could/should use MutableBigIntegers directly for the
  2742. * reduction loop.
  2743. *<ul>
  2744. * @return the length of the unscaled value, in decimal digits
  2745. */
  2746. private int digitLength() {
  2747. if (intVal.signum() == 0) // 0 is one decimal digit
  2748. return 1;
  2749. // we have a nonzero magnitude
  2750. BigInteger work = intVal;
  2751. int digits = 0; // counter
  2752. for (;work.mag.length>1;) {
  2753. // here when more than one integer in the magnitude; divide
  2754. // by a billion (reduce by 9 digits) and try again
  2755. work = work.divide(TENPOWERS[9]);
  2756. digits += 9;
  2757. if (work.signum() == 0) // the division was exact
  2758. return digits; // (a power of a billion)
  2759. }
  2760. // down to a simple nonzero integer
  2761. digits += intLength(work.mag[0]);
  2762. // System.out.println("digitLength... "+this+" -> "+digits);
  2763. return digits;
  2764. }
  2765. /**
  2766. * Returns the length of an unsigned <tt>int</tt>, in decimal digits.
  2767. * @param i the <tt>int</tt> (treated as unsigned)
  2768. * @return the length of the unscaled value, in decimal digits
  2769. */
  2770. private int intLength(int i) {
  2771. int digits;
  2772. if (i < 0) { // 'negative' is 10 digits unsigned
  2773. digits = 10;
  2774. } else { // positive integer
  2775. // binary search, weighted low (maximum 4 tests)
  2776. if (i < 10000) {
  2777. if (i < 100) {
  2778. if (i < 10) digits = 1;
  2779. else digits = 2;
  2780. } else {
  2781. if (i < 1000) digits = 3;
  2782. else digits = 4;
  2783. }
  2784. } else {
  2785. if (i < 1000000) {
  2786. if (i < 100000) digits = 5;
  2787. else digits = 6;
  2788. } else {
  2789. if (i < 100000000) {
  2790. if (i < 10000000) digits = 7;
  2791. else digits = 8;
  2792. } else {
  2793. if (i < 1000000000) digits = 9;
  2794. else digits = 10;
  2795. }
  2796. }
  2797. }
  2798. }
  2799. return digits;
  2800. }
  2801. /**
  2802. * Remove insignificant trailing zeros from this
  2803. * <tt>BigDecimal</tt> until the preferred scale is reached or no
  2804. * more zeros can be removed. If the preferred scale is less than
  2805. * Integer.MIN_VALUE, all the trailing zeros will be removed.
  2806. *
  2807. * <tt>BigInteger</tt> assistance could help, here?
  2808. *
  2809. * @return this <tt>BigDecimal</tt> with a scale possibly reduced
  2810. * to be closed to the preferred scale.
  2811. */
  2812. private BigDecimal stripZerosToMatchScale(long preferredScale) {
  2813. BigInteger qr[]; // quotient-remainder pair
  2814. while ( intVal.abs().compareTo(BigInteger.TEN) >= 0 &&
  2815. scale > preferredScale) {
  2816. if (intVal.testBit(0))
  2817. break; // odd number cannot end in 0
  2818. qr = intVal.divideAndRemainder(BigInteger.TEN);
  2819. if (qr[1].signum() != 0)
  2820. break; // non-0 remainder
  2821. intVal=qr[0];
  2822. scale = checkScale((long)scale-1); // could Overflow
  2823. if (precision > 0) // adjust precision if known
  2824. precision--;
  2825. }
  2826. return this;
  2827. }
  2828. /**
  2829. * Check a scale for Underflow or Overflow
  2830. *
  2831. * @param val The new scale.
  2832. * @throws ArithmeticException (overflow or underflow) if the new
  2833. * scale is out of range.
  2834. * @return validated scale as an int.
  2835. */
  2836. private int checkScale(long val) {
  2837. if ((int)val != val) {
  2838. if ((this.intVal != null && this.signum() != 0) ||
  2839. this.intVal == null ) {
  2840. if (val > Integer.MAX_VALUE)
  2841. throw new ArithmeticException("Underflow");
  2842. if (val < Integer.MIN_VALUE)
  2843. throw new ArithmeticException("Overflow");
  2844. } else {
  2845. return (val > Integer.MAX_VALUE)?Integer.MAX_VALUE:Integer.MIN_VALUE;
  2846. }
  2847. }
  2848. return (int)val;
  2849. }
  2850. /**
  2851. * Round an operand; used only if digits > 0. Does not change
  2852. * <tt>this</tt> if rounding is needed a new <tt>BigDecimal</tt>
  2853. * is created and returned.
  2854. *
  2855. * @param mc the context to use.
  2856. * @throws ArithmeticException if the result is inexact but the
  2857. * rounding mode is <tt>UNNECESSARY</tt>.
  2858. */
  2859. private BigDecimal roundOp(MathContext mc) {
  2860. BigDecimal rounded = doRound(mc);
  2861. return rounded;
  2862. }
  2863. /** Round this BigDecimal according to the MathContext settings;
  2864. * used only if precision > 0.
  2865. *
  2866. * @param mc the context to use.
  2867. * @throws ArithmeticException if the rounding mode is
  2868. * <tt>RoundingMode.UNNECESSARY</tt> and the
  2869. * <tt>BigDecimal</tt> operation would require rounding.
  2870. */
  2871. private void roundThis(MathContext mc) {
  2872. BigDecimal rounded = doRound(mc);
  2873. if (rounded == this) // wasn't rounded
  2874. return;
  2875. this.intVal = rounded.intVal;
  2876. this.scale = rounded.scale;
  2877. this.precision = rounded.precision;
  2878. return;
  2879. }
  2880. /**
  2881. * Returns a <tt>BigDecimal</tt> rounded according to the
  2882. * MathContext settings; used only if <tt>mc.precision>0</tt>.
  2883. * Does not change <tt>this</tt> if rounding is needed a new
  2884. * <tt>BigDecimal</tt> is created and returned.
  2885. *
  2886. * @param mc the context to use.
  2887. * @return a <tt>BigDecimal</tt> rounded according to the MathContext
  2888. * settings. May return this, if no rounding needed.
  2889. * @throws ArithmeticException if the rounding mode is
  2890. * <tt>RoundingMode.UNNECESSARY</tt> and the
  2891. * result is inexact.
  2892. */
  2893. private BigDecimal doRound(MathContext mc) {
  2894. if (precision == 0) {
  2895. if (mc.roundingMax != null
  2896. && intVal.compareTo(mc.roundingMax) < 0
  2897. && intVal.compareTo(mc.roundingMin) > 0)
  2898. return this; // no rounding needed
  2899. precision(); // find it
  2900. }
  2901. int drop = precision - mc.precision; // digits to discard
  2902. if (drop <= 0) // we fit
  2903. return this;
  2904. BigDecimal rounded = dropDigits(mc, drop);
  2905. // we need to double-check, in case of the 999=>1000 case
  2906. return rounded.doRound(mc);
  2907. }
  2908. /**
  2909. * Removes digits from the significand of a <tt>BigDecimal</tt>,
  2910. * rounding according to the MathContext settings. Does not
  2911. * change <tt>this</tt> a new <tt>BigDecimal</tt> is always
  2912. * created and returned.
  2913. *
  2914. * <p>Actual rounding is carried out, as before, by the divide
  2915. * method, as this minimized code changes. It might be more
  2916. * efficient in most cases to move rounding to here, so we can do
  2917. * a round-to-length rather than round-to-scale.
  2918. *
  2919. * @param mc the context to use.
  2920. * @param drop the number of digits to drop, must be > 0
  2921. * @return a <tt>BigDecimal</tt> rounded according to the MathContext
  2922. * settings. May return <tt>this</tt>, if no rounding needed.
  2923. * @throws ArithmeticException if the rounding mode is
  2924. * <tt>RoundingMode.UNNECESSARY</tt> and the
  2925. * result is inexact.
  2926. */
  2927. private BigDecimal dropDigits(MathContext mc, int drop) {
  2928. // here if we need to round; make the divisor = 10**drop)
  2929. // [calculating the BigInteger here saves setScale later]
  2930. BigDecimal divisor = new BigDecimal(tenToThe(drop), 0);
  2931. // divide to same scale to force round to length
  2932. BigDecimal rounded = this.divide(divisor, scale,
  2933. mc.roundingMode.oldMode);
  2934. rounded.scale -= drop; // adjust the scale
  2935. return rounded;
  2936. }
  2937. }