PageRenderTime 35ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/trunk/JavApi/java/math/BigDecimal.cs

#
C# | 3036 lines | 1445 code | 164 blank | 1427 comment | 459 complexity | e336d87ccc04bf8517a4b6b2029237be MD5 | raw file
Possible License(s): Apache-2.0, BSD-3-Clause
  1. /*
  2. * Licensed under the Apache License, Version 2.0 (the "License");
  3. * you may not use this file except in compliance with the License.
  4. * You may obtain a copy of the License at
  5. *
  6. * http://www.apache.org/licenses/LICENSE-2.0
  7. *
  8. * Unless required by applicable law or agreed to in writing, software
  9. * distributed under the License is distributed on an "AS IS" BASIS,
  10. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. * See the License for the specific language governing permissions and
  12. * limitations under the License.
  13. *
  14. */
  15. using System;
  16. using System.Text;
  17. using java = biz.ritter.javapi;
  18. namespace biz.ritter.javapi.math
  19. {
  20. /**
  21. * This class represents immutable arbitrary precision decimal numbers. Each
  22. * {@code BigDecimal} instance is represented with a unscaled arbitrary
  23. * precision mantissa (the unscaled value) and a scale. The value of the {@code
  24. * BigDecimal} is {@code unscaledValue} 10^(-{@code scale}).
  25. */
  26. [Serializable]
  27. public class BigDecimal : java.lang.Number, java.lang.Comparable<BigDecimal>, java.io.Serializable {
  28. /**
  29. * The constant zero as a {@code BigDecimal}.
  30. */
  31. public static readonly BigDecimal ZERO = new BigDecimal(0, 0);
  32. /**
  33. * The constant one as a {@code BigDecimal}.
  34. */
  35. public static readonly BigDecimal ONE = new BigDecimal(1, 0);
  36. /**
  37. * The constant ten as a {@code BigDecimal}.
  38. */
  39. public static readonly BigDecimal TEN = new BigDecimal(10, 0);
  40. /**
  41. * Rounding mode where positive values are rounded towards positive infinity
  42. * and negative values towards negative infinity.
  43. *
  44. * @see RoundingMode#UP
  45. */
  46. public const int ROUND_UP = 0;
  47. /**
  48. * Rounding mode where the values are rounded towards zero.
  49. *
  50. * @see RoundingMode#DOWN
  51. */
  52. public const int ROUND_DOWN = 1;
  53. /**
  54. * Rounding mode to round towards positive infinity. For positive values
  55. * this rounding mode behaves as {@link #ROUND_UP}, for negative values as
  56. * {@link #ROUND_DOWN}.
  57. *
  58. * @see RoundingMode#CEILING
  59. */
  60. public const int ROUND_CEILING = 2;
  61. /**
  62. * Rounding mode to round towards negative infinity. For positive values
  63. * this rounding mode behaves as {@link #ROUND_DOWN}, for negative values as
  64. * {@link #ROUND_UP}.
  65. *
  66. * @see RoundingMode#FLOOR
  67. */
  68. public const int ROUND_FLOOR = 3;
  69. /**
  70. * Rounding mode where values are rounded towards the nearest neighbor.
  71. * Ties are broken by rounding up.
  72. *
  73. * @see RoundingMode#HALF_UP
  74. */
  75. public const int ROUND_HALF_UP = 4;
  76. /**
  77. * Rounding mode where values are rounded towards the nearest neighbor.
  78. * Ties are broken by rounding down.
  79. *
  80. * @see RoundingMode#HALF_DOWN
  81. */
  82. public const int ROUND_HALF_DOWN = 5;
  83. /**
  84. * Rounding mode where values are rounded towards the nearest neighbor.
  85. * Ties are broken by rounding to the even neighbor.
  86. *
  87. * @see RoundingMode#HALF_EVEN
  88. */
  89. public const int ROUND_HALF_EVEN = 6;
  90. /**
  91. * Rounding mode where the rounding operations throws an {@code
  92. * ArithmeticException} for the case that rounding is necessary, i.e. for
  93. * the case that the value cannot be represented exactly.
  94. *
  95. * @see RoundingMode#UNNECESSARY
  96. */
  97. public const int ROUND_UNNECESSARY = 7;
  98. /** This is the serialVersionUID used by the sun implementation. */
  99. private static readonly long serialVersionUID = 6108874887143696463L;
  100. /** The double closer to <code>Log10(2)</code>. */
  101. private static readonly double LOG10_2 = 0.3010299956639812;
  102. /** The <code>String</code> representation is cached. */
  103. [NonSerialized]
  104. private String toStringImage = null;
  105. /** Cache for the hash code. */
  106. [NonSerialized]
  107. private int hashCode = 0;
  108. /**
  109. * An array with powers of five that fit in the type <code>long</code>
  110. * (<code>5^0,5^1,...,5^27</code>).
  111. */
  112. private static readonly BigInteger[] FIVE_POW;
  113. /**
  114. * An array with powers of ten that fit in the type <code>long</code>
  115. * (<code>10^0,10^1,...,10^18</code>).
  116. */
  117. private static readonly BigInteger []TEN_POW;
  118. /**
  119. * An array with powers of ten that fit in the type <code>long</code>
  120. * (<code>10^0,10^1,...,10^18</code>).
  121. */
  122. private static readonly long[] LONG_TEN_POW = new long[]
  123. { 1L,
  124. 10L,
  125. 100L,
  126. 1000L,
  127. 10000L,
  128. 100000L,
  129. 1000000L,
  130. 10000000L,
  131. 100000000L,
  132. 1000000000L,
  133. 10000000000L,
  134. 100000000000L,
  135. 1000000000000L,
  136. 10000000000000L,
  137. 100000000000000L,
  138. 1000000000000000L,
  139. 10000000000000000L,
  140. 100000000000000000L,
  141. 1000000000000000000L, };
  142. private static readonly long[] LONG_FIVE_POW = new long[]
  143. { 1L,
  144. 5L,
  145. 25L,
  146. 125L,
  147. 625L,
  148. 3125L,
  149. 15625L,
  150. 78125L,
  151. 390625L,
  152. 1953125L,
  153. 9765625L,
  154. 48828125L,
  155. 244140625L,
  156. 1220703125L,
  157. 6103515625L,
  158. 30517578125L,
  159. 152587890625L,
  160. 762939453125L,
  161. 3814697265625L,
  162. 19073486328125L,
  163. 95367431640625L,
  164. 476837158203125L,
  165. 2384185791015625L,
  166. 11920928955078125L,
  167. 59604644775390625L,
  168. 298023223876953125L,
  169. 1490116119384765625L,
  170. 7450580596923828125L, };
  171. private static readonly int[] LONG_FIVE_POW_BIT_LENGTH = new int[LONG_FIVE_POW.Length];
  172. private static readonly int[] LONG_TEN_POW_BIT_LENGTH = new int[LONG_TEN_POW.Length];
  173. private static readonly int BI_SCALED_BY_ZERO_LENGTH = 11;
  174. /**
  175. * An array with the first <code>BigInteger</code> scaled by zero.
  176. * (<code>[0,0],[1,0],...,[10,0]</code>).
  177. */
  178. private static readonly BigDecimal[] BI_SCALED_BY_ZERO = new BigDecimal[BI_SCALED_BY_ZERO_LENGTH];
  179. /**
  180. * An array with the zero number scaled by the first positive scales.
  181. * (<code>0*10^0, 0*10^1, ..., 0*10^10</code>).
  182. */
  183. private static readonly BigDecimal []ZERO_SCALED_BY = new BigDecimal[11];
  184. /** An array filled with characters <code>'0'</code>. */
  185. private static readonly char[] CH_ZEROS = new char[100];
  186. static BigDecimal() {
  187. // To fill all static arrays.
  188. int i = 0;
  189. for (; i < ZERO_SCALED_BY.Length; i++) {
  190. BI_SCALED_BY_ZERO[i] = new BigDecimal(i, 0);
  191. ZERO_SCALED_BY[i] = new BigDecimal(0, i);
  192. CH_ZEROS[i] = '0';
  193. }
  194. for (; i < CH_ZEROS.Length; i++) {
  195. CH_ZEROS[i] = '0';
  196. }
  197. for(int j=0; j<LONG_FIVE_POW_BIT_LENGTH.Length; j++) {
  198. LONG_FIVE_POW_BIT_LENGTH[j] = bitLength(LONG_FIVE_POW[j]);
  199. }
  200. for(int j=0; j<LONG_TEN_POW_BIT_LENGTH.Length; j++) {
  201. LONG_TEN_POW_BIT_LENGTH[j] = bitLength(LONG_TEN_POW[j]);
  202. }
  203. // Taking the references of useful powers.
  204. TEN_POW = Multiplication.bigTenPows;
  205. FIVE_POW = Multiplication.bigFivePows;
  206. }
  207. /**
  208. * The arbitrary precision integer (unscaled value) in the internal
  209. * representation of {@code BigDecimal}.
  210. */
  211. private BigInteger intVal;
  212. [NonSerialized]
  213. private int bitLengthJ;
  214. [NonSerialized]
  215. private long smallValue;
  216. /**
  217. * The 32-bit integer scale in the internal representation of {@code BigDecimal}.
  218. */
  219. private int scaleJ;
  220. /**
  221. * Represent the number of decimal digits in the unscaled value. This
  222. * precision is calculated the first time, and used in the following calls
  223. * of method <code>precision()</code>. Note that some call to the private
  224. * method <code>inplaceRound()</code> could update this field.
  225. *
  226. * @see #precision()
  227. * @see #inplaceRound(MathContext)
  228. */
  229. [NonSerialized]
  230. private int precisionJ = 0;
  231. private BigDecimal(long smallValue, int scale){
  232. this.smallValue = smallValue;
  233. this.scaleJ = scale;
  234. this.bitLengthJ = bitLength(smallValue);
  235. }
  236. private BigDecimal(int smallValue, int scale){
  237. this.smallValue = smallValue;
  238. this.scaleJ = scale;
  239. this.bitLengthJ = bitLength(smallValue);
  240. }
  241. /**
  242. * Constructs a new {@code BigDecimal} instance from a string representation
  243. * given as a character array.
  244. *
  245. * @param in
  246. * array of characters containing the string representation of
  247. * this {@code BigDecimal}.
  248. * @param offset
  249. * first index to be copied.
  250. * @param len
  251. * number of characters to be used.
  252. * @throws NullPointerException
  253. * if {@code in == null}.
  254. * @throws NumberFormatException
  255. * if {@code offset < 0} or {@code len <= 0} or {@code
  256. * offset+len-1 < 0} or {@code offset+len-1 >= in.length}.
  257. * @throws NumberFormatException
  258. * if in does not contain a valid string representation of a big
  259. * decimal.
  260. */
  261. public BigDecimal(char[] inJ, int offset, int len) {
  262. int begin = offset; // first index to be copied
  263. int last = offset + (len - 1); // last index to be copied
  264. String scaleString = null; // buffer for scale
  265. StringBuilder unscaledBuffer; // buffer for unscaled value
  266. long newScale; // the new scale
  267. if (inJ == null) {
  268. throw new java.lang.NullPointerException();
  269. }
  270. if ((last >= inJ.Length) || (offset < 0) || (len <= 0) || (last < 0)) {
  271. throw new java.lang.NumberFormatException();
  272. }
  273. unscaledBuffer = new StringBuilder(len);
  274. int bufLength = 0;
  275. // To skip a possible '+' symbol
  276. if ((offset <= last) && (inJ[offset] == '+')) {
  277. offset++;
  278. begin++;
  279. }
  280. int counter = 0;
  281. bool wasNonZero = false;
  282. // Accumulating all digits until a possible decimal point
  283. for (; (offset <= last) && (inJ[offset] != '.')
  284. && (inJ[offset] != 'e') && (inJ[offset] != 'E'); offset++) {
  285. if (!wasNonZero) {
  286. if (inJ[offset] == '0') {
  287. counter++;
  288. } else {
  289. wasNonZero = true;
  290. }
  291. }
  292. }
  293. unscaledBuffer.Append(inJ, begin, offset - begin);
  294. bufLength += offset - begin;
  295. // A decimal point was found
  296. if ((offset <= last) && (inJ[offset] == '.')) {
  297. offset++;
  298. // Accumulating all digits until a possible exponent
  299. begin = offset;
  300. for (; (offset <= last) && (inJ[offset] != 'e')
  301. && (inJ[offset] != 'E'); offset++) {
  302. if (!wasNonZero) {
  303. if (inJ[offset] == '0') {
  304. counter++;
  305. } else {
  306. wasNonZero = true;
  307. }
  308. }
  309. }
  310. scaleJ = offset - begin;
  311. bufLength +=scaleJ;
  312. unscaledBuffer.Append(inJ, begin, scaleJ);
  313. } else {
  314. scaleJ = 0;
  315. }
  316. // An exponent was found
  317. if ((offset <= last) && ((inJ[offset] == 'e') || (inJ[offset] == 'E'))) {
  318. offset++;
  319. // Checking for a possible sign of scale
  320. begin = offset;
  321. if ((offset <= last) && (inJ[offset] == '+')) {
  322. offset++;
  323. if ((offset <= last) && (inJ[offset] != '-')) {
  324. begin++;
  325. }
  326. }
  327. // Accumulating all remaining digits
  328. scaleString = java.lang.StringJ.valueOf(inJ, begin, last + 1 - begin).ToString();
  329. // Checking if the scale is defined
  330. newScale = (long)scaleJ - java.lang.Integer.parseInt(scaleString);
  331. scaleJ = (int)newScale;
  332. if (newScale != scaleJ) {
  333. // math.02=Scale out of range.
  334. throw new java.lang.NumberFormatException("Scale out of range."); //$NON-NLS-1$
  335. }
  336. }
  337. // Parsing the unscaled value
  338. if (bufLength < 19) {
  339. smallValue = java.lang.Long.parseLong(unscaledBuffer.toString());
  340. bitLengthJ = bitLength(smallValue);
  341. } else {
  342. setUnscaledValue(new BigInteger(unscaledBuffer.toString()));
  343. }
  344. precisionJ = unscaledBuffer.Length - counter;
  345. if (unscaledBuffer[0] == '-') {
  346. precisionJ --;
  347. }
  348. }
  349. /**
  350. * Constructs a new {@code BigDecimal} instance from a string representation
  351. * given as a character array.
  352. *
  353. * @param in
  354. * array of characters containing the string representation of
  355. * this {@code BigDecimal}.
  356. * @param offset
  357. * first index to be copied.
  358. * @param len
  359. * number of characters to be used.
  360. * @param mc
  361. * rounding mode and precision for the result of this operation.
  362. * @throws NullPointerException
  363. * if {@code in == null}.
  364. * @throws NumberFormatException
  365. * if {@code offset < 0} or {@code len <= 0} or {@code
  366. * offset+len-1 < 0} or {@code offset+len-1 >= in.length}.
  367. * @throws NumberFormatException
  368. * if {@code in} does not contain a valid string representation
  369. * of a big decimal.
  370. * @throws ArithmeticException
  371. * if {@code mc.precision > 0} and {@code mc.roundingMode ==
  372. * UNNECESSARY} and the new big decimal cannot be represented
  373. * within the given precision without rounding.
  374. */
  375. public BigDecimal(char[] inJ, int offset, int len, MathContext mc) :this(inJ, offset, len){
  376. inplaceRound(mc);
  377. }
  378. /**
  379. * Constructs a new {@code BigDecimal} instance from a string representation
  380. * given as a character array.
  381. *
  382. * @param in
  383. * array of characters containing the string representation of
  384. * this {@code BigDecimal}.
  385. * @throws NullPointerException
  386. * if {@code in == null}.
  387. * @throws NumberFormatException
  388. * if {@code in} does not contain a valid string representation
  389. * of a big decimal.
  390. */
  391. public BigDecimal(char[] inJ) :this(inJ, 0, inJ.Length){
  392. }
  393. /**
  394. * Constructs a new {@code BigDecimal} instance from a string representation
  395. * given as a character array. The result is rounded according to the
  396. * specified math context.
  397. *
  398. * @param in
  399. * array of characters containing the string representation of
  400. * this {@code BigDecimal}.
  401. * @param mc
  402. * rounding mode and precision for the result of this operation.
  403. * @throws NullPointerException
  404. * if {@code in == null}.
  405. * @throws NumberFormatException
  406. * if {@code in} does not contain a valid string representation
  407. * of a big decimal.
  408. * @throws ArithmeticException
  409. * if {@code mc.precision > 0} and {@code mc.roundingMode ==
  410. * UNNECESSARY} and the new big decimal cannot be represented
  411. * within the given precision without rounding.
  412. */
  413. public BigDecimal(char[] inJ, MathContext mc) :this(inJ, 0, inJ.Length){
  414. inplaceRound(mc);
  415. }
  416. /**
  417. * Constructs a new {@code BigDecimal} instance from a string
  418. * representation.
  419. *
  420. * @param val
  421. * string containing the string representation of this {@code
  422. * BigDecimal}.
  423. * @throws NumberFormatException
  424. * if {@code val} does not contain a valid string representation
  425. * of a big decimal.
  426. */
  427. public BigDecimal(String val) :this(val.toCharArray(), 0, val.length()){
  428. }
  429. /**
  430. * Constructs a new {@code BigDecimal} instance from a string
  431. * representation. The result is rounded according to the specified math
  432. * context.
  433. *
  434. * @param val
  435. * string containing the string representation of this {@code
  436. * BigDecimal}.
  437. * @param mc
  438. * rounding mode and precision for the result of this operation.
  439. * @throws NumberFormatException
  440. * if {@code val} does not contain a valid string representation
  441. * of a big decimal.
  442. * @throws ArithmeticException
  443. * if {@code mc.precision > 0} and {@code mc.roundingMode ==
  444. * UNNECESSARY} and the new big decimal cannot be represented
  445. * within the given precision without rounding.
  446. */
  447. public BigDecimal(String val, MathContext mc) :this(val.toCharArray(), 0, val.length()){
  448. inplaceRound(mc);
  449. }
  450. /**
  451. * Constructs a new {@code BigDecimal} instance from the 64bit double
  452. * {@code val}. The constructed big decimal is equivalent to the given
  453. * double. For example, {@code new BigDecimal(0.1)} is equal to {@code
  454. * 0.1000000000000000055511151231257827021181583404541015625}. This happens
  455. * as {@code 0.1} cannot be represented exactly in binary.
  456. * <p>
  457. * To generate a big decimal instance which is equivalent to {@code 0.1} use
  458. * the {@code BigDecimal(String)} constructor.
  459. *
  460. * @param val
  461. * double value to be converted to a {@code BigDecimal} instance.
  462. * @throws NumberFormatException
  463. * if {@code val} is infinity or not a number.
  464. */
  465. public BigDecimal(double val) {
  466. if (java.lang.Double.isInfinite(val) || java.lang.Double.isNaN(val)) {
  467. // math.03=Infinity or NaN
  468. throw new java.lang.NumberFormatException("Infinity or NaN"); //$NON-NLS-1$
  469. }
  470. long bits = java.lang.Double.doubleToLongBits(val); // IEEE-754
  471. long mantisa;
  472. int trailingZeros;
  473. // Extracting the exponent, note that the bias is 1023
  474. scaleJ = 1075 - (int)((bits >> 52) & 0x7FFL);
  475. // Extracting the 52 bits of the mantisa.
  476. mantisa = (scaleJ == 1075) ? (bits & 0xFFFFFFFFFFFFFL) << 1
  477. : (bits & 0xFFFFFFFFFFFFFL) | 0x10000000000000L;
  478. if (mantisa == 0) {
  479. scaleJ = 0;
  480. precisionJ = 1;
  481. }
  482. // To simplify all factors '2' in the mantisa
  483. if (scaleJ > 0) {
  484. trailingZeros = java.lang.Math.min(scaleJ, java.lang.Long.numberOfTrailingZeros(mantisa));
  485. mantisa= java.dotnet.lang.Operator.shiftRightUnsignet(mantisa, trailingZeros);
  486. scaleJ -= trailingZeros;
  487. }
  488. // Calculating the new unscaled value and the new scale
  489. if((bits >> 63) != 0) {
  490. mantisa = -mantisa;
  491. }
  492. int mantisaBits = bitLength(mantisa);
  493. if (scaleJ < 0) {
  494. bitLengthJ = mantisaBits == 0 ? 0 : mantisaBits - scaleJ;
  495. if(bitLengthJ < 64) {
  496. smallValue = mantisa << (-scaleJ);
  497. } else {
  498. intVal = BigInteger.valueOf(mantisa).shiftLeft(-scaleJ);
  499. }
  500. scaleJ = 0;
  501. } else if (scaleJ > 0) {
  502. // m * 2^e = (m * 5^(-e)) * 10^e
  503. if(scaleJ < LONG_FIVE_POW.Length
  504. && mantisaBits+LONG_FIVE_POW_BIT_LENGTH[scaleJ] < 64) {
  505. smallValue = mantisa * LONG_FIVE_POW[scaleJ];
  506. bitLengthJ = bitLength(smallValue);
  507. } else {
  508. setUnscaledValue(Multiplication.multiplyByFivePow(BigInteger.valueOf(mantisa), scaleJ));
  509. }
  510. } else { // scale == 0
  511. smallValue = mantisa;
  512. bitLengthJ = mantisaBits;
  513. }
  514. }
  515. /**
  516. * Constructs a new {@code BigDecimal} instance from the 64bit double
  517. * {@code val}. The constructed big decimal is equivalent to the given
  518. * double. For example, {@code new BigDecimal(0.1)} is equal to {@code
  519. * 0.1000000000000000055511151231257827021181583404541015625}. This happens
  520. * as {@code 0.1} cannot be represented exactly in binary.
  521. * <p>
  522. * To generate a big decimal instance which is equivalent to {@code 0.1} use
  523. * the {@code BigDecimal(String)} constructor.
  524. *
  525. * @param val
  526. * double value to be converted to a {@code BigDecimal} instance.
  527. * @param mc
  528. * rounding mode and precision for the result of this operation.
  529. * @throws NumberFormatException
  530. * if {@code val} is infinity or not a number.
  531. * @throws ArithmeticException
  532. * if {@code mc.precision > 0} and {@code mc.roundingMode ==
  533. * UNNECESSARY} and the new big decimal cannot be represented
  534. * within the given precision without rounding.
  535. */
  536. public BigDecimal(double val, MathContext mc) :this(val){
  537. inplaceRound(mc);
  538. }
  539. /**
  540. * Constructs a new {@code BigDecimal} instance from the given big integer
  541. * {@code val}. The scale of the result is {@code 0}.
  542. *
  543. * @param val
  544. * {@code BigInteger} value to be converted to a {@code
  545. * BigDecimal} instance.
  546. */
  547. public BigDecimal(BigInteger val):this(val, 0){
  548. }
  549. /**
  550. * Constructs a new {@code BigDecimal} instance from the given big integer
  551. * {@code val}. The scale of the result is {@code 0}.
  552. *
  553. * @param val
  554. * {@code BigInteger} value to be converted to a {@code
  555. * BigDecimal} instance.
  556. * @param mc
  557. * rounding mode and precision for the result of this operation.
  558. * @throws ArithmeticException
  559. * if {@code mc.precision > 0} and {@code mc.roundingMode ==
  560. * UNNECESSARY} and the new big decimal cannot be represented
  561. * within the given precision without rounding.
  562. */
  563. public BigDecimal(BigInteger val, MathContext mc) :this(val){
  564. inplaceRound(mc);
  565. }
  566. /**
  567. * Constructs a new {@code BigDecimal} instance from a given unscaled value
  568. * {@code unscaledVal} and a given scale. The value of this instance is
  569. * {@code unscaledVal} 10^(-{@code scale}).
  570. *
  571. * @param unscaledVal
  572. * {@code BigInteger} representing the unscaled value of this
  573. * {@code BigDecimal} instance.
  574. * @param scale
  575. * scale of this {@code BigDecimal} instance.
  576. * @throws NullPointerException
  577. * if {@code unscaledVal == null}.
  578. */
  579. public BigDecimal(BigInteger unscaledVal, int scale) {
  580. if (unscaledVal == null) {
  581. throw new java.lang.NullPointerException();
  582. }
  583. this.scaleJ = scale;
  584. setUnscaledValue(unscaledVal);
  585. }
  586. /**
  587. * Constructs a new {@code BigDecimal} instance from a given unscaled value
  588. * {@code unscaledVal} and a given scale. The value of this instance is
  589. * {@code unscaledVal} 10^(-{@code scale}). The result is rounded according
  590. * to the specified math context.
  591. *
  592. * @param unscaledVal
  593. * {@code BigInteger} representing the unscaled value of this
  594. * {@code BigDecimal} instance.
  595. * @param scale
  596. * scale of this {@code BigDecimal} instance.
  597. * @param mc
  598. * rounding mode and precision for the result of this operation.
  599. * @throws ArithmeticException
  600. * if {@code mc.precision > 0} and {@code mc.roundingMode ==
  601. * UNNECESSARY} and the new big decimal cannot be represented
  602. * within the given precision without rounding.
  603. * @throws NullPointerException
  604. * if {@code unscaledVal == null}.
  605. */
  606. public BigDecimal(BigInteger unscaledVal, int scale, MathContext mc) :this(unscaledVal, scale){
  607. inplaceRound(mc);
  608. }
  609. /**
  610. * Constructs a new {@code BigDecimal} instance from the given int
  611. * {@code val}. The scale of the result is 0.
  612. *
  613. * @param val
  614. * int value to be converted to a {@code BigDecimal} instance.
  615. */
  616. public BigDecimal(int val) :this(val,0){
  617. }
  618. /**
  619. * Constructs a new {@code BigDecimal} instance from the given int {@code
  620. * val}. The scale of the result is {@code 0}. The result is rounded
  621. * according to the specified math context.
  622. *
  623. * @param val
  624. * int value to be converted to a {@code BigDecimal} instance.
  625. * @param mc
  626. * rounding mode and precision for the result of this operation.
  627. * @throws ArithmeticException
  628. * if {@code mc.precision > 0} and {@code c.roundingMode ==
  629. * UNNECESSARY} and the new big decimal cannot be represented
  630. * within the given precision without rounding.
  631. */
  632. public BigDecimal(int val, MathContext mc) :this(val,0){
  633. inplaceRound(mc);
  634. }
  635. /**
  636. * Constructs a new {@code BigDecimal} instance from the given long {@code
  637. * val}. The scale of the result is {@code 0}.
  638. *
  639. * @param val
  640. * long value to be converted to a {@code BigDecimal} instance.
  641. */
  642. public BigDecimal(long val) :this(val,0){
  643. }
  644. /**
  645. * Constructs a new {@code BigDecimal} instance from the given long {@code
  646. * val}. The scale of the result is {@code 0}. The result is rounded
  647. * according to the specified math context.
  648. *
  649. * @param val
  650. * long value to be converted to a {@code BigDecimal} instance.
  651. * @param mc
  652. * rounding mode and precision for the result of this operation.
  653. * @throws ArithmeticException
  654. * if {@code mc.precision > 0} and {@code mc.roundingMode ==
  655. * UNNECESSARY} and the new big decimal cannot be represented
  656. * within the given precision without rounding.
  657. */
  658. public BigDecimal(long val, MathContext mc) :this(val){
  659. inplaceRound(mc);
  660. }
  661. /* Public Methods */
  662. /**
  663. * Returns a new {@code BigDecimal} instance whose value is equal to {@code
  664. * unscaledVal} 10^(-{@code scale}). The scale of the result is {@code
  665. * scale}, and its unscaled value is {@code unscaledVal}.
  666. *
  667. * @param unscaledVal
  668. * unscaled value to be used to construct the new {@code
  669. * BigDecimal}.
  670. * @param scale
  671. * scale to be used to construct the new {@code BigDecimal}.
  672. * @return {@code BigDecimal} instance with the value {@code unscaledVal}*
  673. * 10^(-{@code unscaledVal}).
  674. */
  675. public static BigDecimal valueOf(long unscaledVal, int scale) {
  676. if (scale == 0) {
  677. return valueOf(unscaledVal);
  678. }
  679. if ((unscaledVal == 0) && (scale >= 0)
  680. && (scale < ZERO_SCALED_BY.Length)) {
  681. return ZERO_SCALED_BY[scale];
  682. }
  683. return new BigDecimal(unscaledVal, scale);
  684. }
  685. /**
  686. * Returns a new {@code BigDecimal} instance whose value is equal to {@code
  687. * unscaledVal}. The scale of the result is {@code 0}, and its unscaled
  688. * value is {@code unscaledVal}.
  689. *
  690. * @param unscaledVal
  691. * value to be converted to a {@code BigDecimal}.
  692. * @return {@code BigDecimal} instance with the value {@code unscaledVal}.
  693. */
  694. public static BigDecimal valueOf(long unscaledVal) {
  695. if ((unscaledVal >= 0) && (unscaledVal < BI_SCALED_BY_ZERO_LENGTH)) {
  696. return BI_SCALED_BY_ZERO[(int)unscaledVal];
  697. }
  698. return new BigDecimal(unscaledVal,0);
  699. }
  700. /**
  701. * Returns a new {@code BigDecimal} instance whose value is equal to {@code
  702. * val}. The new decimal is constructed as if the {@code BigDecimal(String)}
  703. * constructor is called with an argument which is equal to {@code
  704. * Double.toString(val)}. For example, {@code valueOf("0.1")} is converted to
  705. * (unscaled=1, scale=1), although the double {@code 0.1} cannot be
  706. * represented exactly as a double value. In contrast to that, a new {@code
  707. * BigDecimal(0.1)} instance has the value {@code
  708. * 0.1000000000000000055511151231257827021181583404541015625} with an
  709. * unscaled value {@code 1000000000000000055511151231257827021181583404541015625}
  710. * and the scale {@code 55}.
  711. *
  712. * @param val
  713. * double value to be converted to a {@code BigDecimal}.
  714. * @return {@code BigDecimal} instance with the value {@code val}.
  715. * @throws NumberFormatException
  716. * if {@code val} is infinite or {@code val} is not a number
  717. */
  718. public static BigDecimal valueOf(double val) {
  719. if (java.lang.Double.isInfinite(val) || java.lang.Double.isNaN(val)) {
  720. // math.03=Infinity or NaN
  721. throw new java.lang.NumberFormatException("Infinity or NaN"); //$NON-NLS-1$
  722. }
  723. return new BigDecimal(java.lang.Double.toString(val));
  724. }
  725. /**
  726. * Returns a new {@code BigDecimal} whose value is {@code this + augend}.
  727. * The scale of the result is the maximum of the scales of the two
  728. * arguments.
  729. *
  730. * @param augend
  731. * value to be added to {@code this}.
  732. * @return {@code this + augend}.
  733. * @throws NullPointerException
  734. * if {@code augend == null}.
  735. */
  736. public BigDecimal add(BigDecimal augend) {
  737. int diffScale = this.scaleJ - augend.scaleJ;
  738. // Fast return when some operand is zero
  739. if (this.isZero()) {
  740. if (diffScale <= 0) {
  741. return augend;
  742. }
  743. if (augend.isZero()) {
  744. return this;
  745. }
  746. } else if (augend.isZero()) {
  747. if (diffScale >= 0) {
  748. return this;
  749. }
  750. }
  751. // Let be: this = [u1,s1] and augend = [u2,s2]
  752. if (diffScale == 0) {
  753. // case s1 == s2: [u1 + u2 , s1]
  754. if (java.lang.Math.max(this.bitLengthJ, augend.bitLengthJ) + 1 < 64) {
  755. return valueOf(this.smallValue + augend.smallValue, this.scaleJ);
  756. }
  757. return new BigDecimal(this.getUnscaledValue().add(augend.getUnscaledValue()), this.scaleJ);
  758. } else if (diffScale > 0) {
  759. // case s1 > s2 : [(u1 + u2) * 10 ^ (s1 - s2) , s1]
  760. return addAndMult10(this, augend, diffScale);
  761. } else {// case s2 > s1 : [(u2 + u1) * 10 ^ (s2 - s1) , s2]
  762. return addAndMult10(augend, this, -diffScale);
  763. }
  764. }
  765. private static BigDecimal addAndMult10(BigDecimal thisValue,BigDecimal augend, int diffScale) {
  766. if(diffScale < LONG_TEN_POW.Length &&
  767. java.lang.Math.max(thisValue.bitLengthJ,augend.bitLengthJ+LONG_TEN_POW_BIT_LENGTH[diffScale])+1<64) {
  768. return valueOf(thisValue.smallValue+augend.smallValue*LONG_TEN_POW[diffScale],thisValue.scaleJ);
  769. }
  770. return new BigDecimal(thisValue.getUnscaledValue().add(
  771. Multiplication.multiplyByTenPow(augend.getUnscaledValue(),diffScale)), thisValue.scaleJ);
  772. }
  773. /**
  774. * Returns a new {@code BigDecimal} whose value is {@code this + augend}.
  775. * The result is rounded according to the passed context {@code mc}.
  776. *
  777. * @param augend
  778. * value to be added to {@code this}.
  779. * @param mc
  780. * rounding mode and precision for the result of this operation.
  781. * @return {@code this + augend}.
  782. * @throws NullPointerException
  783. * if {@code augend == null} or {@code mc == null}.
  784. */
  785. public BigDecimal add(BigDecimal augend, MathContext mc) {
  786. BigDecimal larger; // operand with the largest unscaled value
  787. BigDecimal smaller; // operand with the smallest unscaled value
  788. BigInteger tempBI;
  789. long diffScale = (long)this.scaleJ - augend.scaleJ;
  790. int largerSignum;
  791. // Some operand is zero or the precision is infinity
  792. if ((augend.isZero()) || (this.isZero())
  793. || (mc.getPrecision() == 0)) {
  794. return add(augend).round(mc);
  795. }
  796. // Cases where there is room for optimizations
  797. if (this.aproxPrecision() < diffScale - 1) {
  798. larger = augend;
  799. smaller = this;
  800. } else if (augend.aproxPrecision() < -diffScale - 1) {
  801. larger = this;
  802. smaller = augend;
  803. } else {// No optimization is done
  804. return add(augend).round(mc);
  805. }
  806. if (mc.getPrecision() >= larger.aproxPrecision()) {
  807. // No optimization is done
  808. return add(augend).round(mc);
  809. }
  810. // Cases where it's unnecessary to add two numbers with very different scales
  811. largerSignum = larger.signum();
  812. if (largerSignum == smaller.signum()) {
  813. tempBI = Multiplication.multiplyByPositiveInt(larger.getUnscaledValue(),10)
  814. .add(BigInteger.valueOf(largerSignum));
  815. } else {
  816. tempBI = larger.getUnscaledValue().subtract(
  817. BigInteger.valueOf(largerSignum));
  818. tempBI = Multiplication.multiplyByPositiveInt(tempBI,10)
  819. .add(BigInteger.valueOf(largerSignum * 9));
  820. }
  821. // Rounding the improved adding
  822. larger = new BigDecimal(tempBI, larger.scaleJ + 1);
  823. return larger.round(mc);
  824. }
  825. /**
  826. * Returns a new {@code BigDecimal} whose value is {@code this - subtrahend}.
  827. * The scale of the result is the maximum of the scales of the two arguments.
  828. *
  829. * @param subtrahend
  830. * value to be subtracted from {@code this}.
  831. * @return {@code this - subtrahend}.
  832. * @throws NullPointerException
  833. * if {@code subtrahend == null}.
  834. */
  835. public BigDecimal subtract(BigDecimal subtrahend) {
  836. int diffScale = this.scaleJ - subtrahend.scaleJ;
  837. // Fast return when some operand is zero
  838. if (this.isZero()) {
  839. if (diffScale <= 0) {
  840. return subtrahend.negate();
  841. }
  842. if (subtrahend.isZero()) {
  843. return this;
  844. }
  845. } else if (subtrahend.isZero()) {
  846. if (diffScale >= 0) {
  847. return this;
  848. }
  849. }
  850. // Let be: this = [u1,s1] and subtrahend = [u2,s2] so:
  851. if (diffScale == 0) {
  852. // case s1 = s2 : [u1 - u2 , s1]
  853. if (java.lang.Math.max(this.bitLengthJ, subtrahend.bitLengthJ) + 1 < 64) {
  854. return valueOf(this.smallValue - subtrahend.smallValue,this.scaleJ);
  855. }
  856. return new BigDecimal(this.getUnscaledValue().subtract(subtrahend.getUnscaledValue()), this.scaleJ);
  857. } else if (diffScale > 0) {
  858. // case s1 > s2 : [ u1 - u2 * 10 ^ (s1 - s2) , s1 ]
  859. if(diffScale < LONG_TEN_POW.Length &&
  860. java.lang.Math.max(this.bitLengthJ,subtrahend.bitLengthJ+LONG_TEN_POW_BIT_LENGTH[diffScale])+1<64) {
  861. return valueOf(this.smallValue-subtrahend.smallValue*LONG_TEN_POW[diffScale],this.scaleJ);
  862. }
  863. return new BigDecimal(this.getUnscaledValue().subtract(
  864. Multiplication.multiplyByTenPow(subtrahend.getUnscaledValue(),diffScale)), this.scaleJ);
  865. } else {// case s2 > s1 : [ u1 * 10 ^ (s2 - s1) - u2 , s2 ]
  866. diffScale = -diffScale;
  867. if(diffScale < LONG_TEN_POW.Length &&
  868. java.lang.Math.max(this.bitLengthJ+LONG_TEN_POW_BIT_LENGTH[diffScale],subtrahend.bitLengthJ)+1<64) {
  869. return valueOf(this.smallValue*LONG_TEN_POW[diffScale]-subtrahend.smallValue,subtrahend.scaleJ);
  870. }
  871. return new BigDecimal(Multiplication.multiplyByTenPow(this.getUnscaledValue(),diffScale)
  872. .subtract(subtrahend.getUnscaledValue()), subtrahend.scaleJ);
  873. }
  874. }
  875. /**
  876. * Returns a new {@code BigDecimal} whose value is {@code this - subtrahend}.
  877. * The result is rounded according to the passed context {@code mc}.
  878. *
  879. * @param subtrahend
  880. * value to be subtracted from {@code this}.
  881. * @param mc
  882. * rounding mode and precision for the result of this operation.
  883. * @return {@code this - subtrahend}.
  884. * @throws NullPointerException
  885. * if {@code subtrahend == null} or {@code mc == null}.
  886. */
  887. public BigDecimal subtract(BigDecimal subtrahend, MathContext mc) {
  888. long diffScale = subtrahend.scaleJ - (long)this.scaleJ;
  889. int thisSignum;
  890. BigDecimal leftOperand; // it will be only the left operand (this)
  891. BigInteger tempBI;
  892. // Some operand is zero or the precision is infinity
  893. if ((subtrahend.isZero()) || (this.isZero())
  894. || (mc.getPrecision() == 0)) {
  895. return subtract(subtrahend).round(mc);
  896. }
  897. // Now: this != 0 and subtrahend != 0
  898. if (subtrahend.aproxPrecision() < diffScale - 1) {
  899. // Cases where it is unnecessary to subtract two numbers with very different scales
  900. if (mc.getPrecision() < this.aproxPrecision()) {
  901. thisSignum = this.signum();
  902. if (thisSignum != subtrahend.signum()) {
  903. tempBI = Multiplication.multiplyByPositiveInt(this.getUnscaledValue(), 10)
  904. .add(BigInteger.valueOf(thisSignum));
  905. } else {
  906. tempBI = this.getUnscaledValue().subtract(BigInteger.valueOf(thisSignum));
  907. tempBI = Multiplication.multiplyByPositiveInt(tempBI, 10)
  908. .add(BigInteger.valueOf(thisSignum * 9));
  909. }
  910. // Rounding the improved subtracting
  911. leftOperand = new BigDecimal(tempBI, this.scaleJ + 1);
  912. return leftOperand.round(mc);
  913. }
  914. }
  915. // No optimization is done
  916. return subtract(subtrahend).round(mc);
  917. }
  918. /**
  919. * Returns a new {@code BigDecimal} whose value is {@code this *
  920. * multiplicand}. The scale of the result is the sum of the scales of the
  921. * two arguments.
  922. *
  923. * @param multiplicand
  924. * value to be multiplied with {@code this}.
  925. * @return {@code this * multiplicand}.
  926. * @throws NullPointerException
  927. * if {@code multiplicand == null}.
  928. */
  929. public BigDecimal multiply(BigDecimal multiplicand) {
  930. long newScale = (long)this.scaleJ + multiplicand.scaleJ;
  931. if ((this.isZero()) || (multiplicand.isZero())) {
  932. return zeroScaledBy(newScale);
  933. }
  934. /* Let be: this = [u1,s1] and multiplicand = [u2,s2] so:
  935. * this x multiplicand = [ s1 * s2 , s1 + s2 ] */
  936. if(this.bitLengthJ + multiplicand.bitLengthJ < 64) {
  937. return valueOf(this.smallValue*multiplicand.smallValue,toIntScale(newScale));
  938. }
  939. return new BigDecimal(this.getUnscaledValue().multiply(
  940. multiplicand.getUnscaledValue()), toIntScale(newScale));
  941. }
  942. /**
  943. * Returns a new {@code BigDecimal} whose value is {@code this *
  944. * multiplicand}. The result is rounded according to the passed context
  945. * {@code mc}.
  946. *
  947. * @param multiplicand
  948. * value to be multiplied with {@code this}.
  949. * @param mc
  950. * rounding mode and precision for the result of this operation.
  951. * @return {@code this * multiplicand}.
  952. * @throws NullPointerException
  953. * if {@code multiplicand == null} or {@code mc == null}.
  954. */
  955. public BigDecimal multiply(BigDecimal multiplicand, MathContext mc) {
  956. BigDecimal result = multiply(multiplicand);
  957. result.inplaceRound(mc);
  958. return result;
  959. }
  960. /**
  961. * Returns a new {@code BigDecimal} whose value is {@code this / divisor}.
  962. * As scale of the result the parameter {@code scale} is used. If rounding
  963. * is required to meet the specified scale, then the specified rounding mode
  964. * {@code roundingMode} is applied.
  965. *
  966. * @param divisor
  967. * value by which {@code this} is divided.
  968. * @param scale
  969. * the scale of the result returned.
  970. * @param roundingMode
  971. * rounding mode to be used to round the result.
  972. * @return {@code this / divisor} rounded according to the given rounding
  973. * mode.
  974. * @throws NullPointerException
  975. * if {@code divisor == null}.
  976. * @throws IllegalArgumentException
  977. * if {@code roundingMode} is not a valid rounding mode.
  978. * @throws ArithmeticException
  979. * if {@code divisor == 0}.
  980. * @throws ArithmeticException
  981. * if {@code roundingMode == ROUND_UNNECESSARY} and rounding is
  982. * necessary according to the given scale.
  983. */
  984. public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode) {
  985. return divide(divisor, scale, RoundingMode.valueOf(roundingMode));
  986. }
  987. /**
  988. * Returns a new {@code BigDecimal} whose value is {@code this / divisor}.
  989. * As scale of the result the parameter {@code scale} is used. If rounding
  990. * is required to meet the specified scale, then the specified rounding mode
  991. * {@code roundingMode} is applied.
  992. *
  993. * @param divisor
  994. * value by which {@code this} is divided.
  995. * @param scale
  996. * the scale of the result returned.
  997. * @param roundingMode
  998. * rounding mode to be used to round the result.
  999. * @return {@code this / divisor} rounded according to the given rounding
  1000. * mode.
  1001. * @throws NullPointerException
  1002. * if {@code divisor == null} or {@code roundingMode == null}.
  1003. * @throws ArithmeticException
  1004. * if {@code divisor == 0}.
  1005. * @throws ArithmeticException
  1006. * if {@code roundingMode == RoundingMode.UNNECESSAR}Y and
  1007. * rounding is necessary according to the given scale and given
  1008. * precision.
  1009. */
  1010. public BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode) {
  1011. // Let be: this = [u1,s1] and divisor = [u2,s2]
  1012. if (roundingMode == null) {
  1013. throw new java.lang.NullPointerException();
  1014. }
  1015. if (divisor.isZero()) {
  1016. // math.04=Division by zero
  1017. throw new java.lang.ArithmeticException("Division by zero"); //$NON-NLS-1$
  1018. }
  1019. long diffScale = ((long)this.scaleJ - divisor.scaleJ) - scale;
  1020. if(this.bitLengthJ < 64 && divisor.bitLengthJ < 64 ) {
  1021. if(diffScale == 0) {
  1022. return dividePrimitiveLongs(this.smallValue,
  1023. divisor.smallValue,
  1024. scale,
  1025. roundingMode );
  1026. } else if(diffScale > 0) {
  1027. if(diffScale < LONG_TEN_POW.Length &&
  1028. divisor.bitLengthJ + LONG_TEN_POW_BIT_LENGTH[(int)diffScale] < 64) {
  1029. return dividePrimitiveLongs(this.smallValue,
  1030. divisor.smallValue*LONG_TEN_POW[(int)diffScale],
  1031. scale,
  1032. roundingMode);
  1033. }
  1034. } else { // diffScale < 0
  1035. if(-diffScale < LONG_TEN_POW.Length &&
  1036. this.bitLengthJ + LONG_TEN_POW_BIT_LENGTH[(int)-diffScale] < 64) {
  1037. return dividePrimitiveLongs(this.smallValue*LONG_TEN_POW[(int)-diffScale],
  1038. divisor.smallValue,
  1039. scale,
  1040. roundingMode);
  1041. }
  1042. }
  1043. }
  1044. BigInteger scaledDividend = this.getUnscaledValue();
  1045. BigInteger scaledDivisor = divisor.getUnscaledValue(); // for scaling of 'u2'
  1046. if (diffScale > 0) {
  1047. // Multiply 'u2' by: 10^((s1 - s2) - scale)
  1048. scaledDivisor = Multiplication.multiplyByTenPow(scaledDivisor, (int)diffScale);
  1049. } else if (diffScale < 0) {
  1050. // Multiply 'u1' by: 10^(scale - (s1 - s2))
  1051. scaledDividend = Multiplication.multiplyByTenPow(scaledDividend, (int)-diffScale);
  1052. }
  1053. return divideBigIntegers(scaledDividend, scaledDivisor, scale, roundingMode);
  1054. }
  1055. private static BigDecimal divideBigIntegers(BigInteger scaledDividend, BigInteger scaledDivisor, int scale, RoundingMode roundingMode) {
  1056. BigInteger[] quotAndRem = scaledDividend.divideAndRemainder(scaledDivisor); // quotient and remainder
  1057. // If after division there is a remainder...
  1058. BigInteger quotient = quotAndRem[0];
  1059. BigInteger remainder = quotAndRem[1];
  1060. if (remainder.signum() == 0) {
  1061. return new BigDecimal(quotient, scale);
  1062. }
  1063. int sign = scaledDividend.signum() * scaledDivisor.signum();
  1064. int compRem; // 'compare to remainder'
  1065. if(scaledDivisor.bitLength() < 63) { // 63 in order to avoid out of long after <<1
  1066. long rem = remainder.longValue();
  1067. long divisor = scaledDivisor.longValue();
  1068. compRem = longCompareTo(java.lang.Math.abs(rem) << 1,java.lang.Math.abs(divisor));
  1069. // To look if there is a carry
  1070. compRem = roundingBehavior(quotient.testBit(0) ? 1 : 0,
  1071. sign * (5 + compRem), roundingMode);
  1072. } else {
  1073. // Checking if: remainder * 2 >= scaledDivisor
  1074. compRem = remainder.abs().shiftLeftOneBit().compareTo(scaledDivisor.abs());
  1075. compRem = roundingBehavior(quotient.testBit(0) ? 1 : 0,
  1076. sign * (5 + compRem), roundingMode);
  1077. }
  1078. if (compRem != 0) {
  1079. if(quotient.bitLength() < 63) {
  1080. return valueOf(quotient.longValue() + compRem,scale);
  1081. }
  1082. quotient = quotient.add(BigInteger.valueOf(compRem));
  1083. return new BigDecimal(quotient, scale);
  1084. }
  1085. // Constructing the result with the appropriate unscaled value
  1086. return new BigDecimal(quotient, scale);
  1087. }
  1088. private static BigDecimal dividePrimitiveLongs(long scaledDividend, long scaledDivisor, int scale, RoundingMode roundingMode) {
  1089. long quotient = scaledDividend / scaledDivisor;
  1090. long remainder = scaledDividend % scaledDivisor;
  1091. int sign = java.lang.Long.signum( scaledDividend ) * java.lang.Long.signum( scaledDivisor );
  1092. if (remainder != 0) {
  1093. // Checking if: remainder * 2 >= scaledDivisor
  1094. int compRem; // 'compare to remainder'
  1095. compRem = longCompareTo(java.lang.Math.abs(remainder) << 1,java.lang.Math.abs(scaledDivisor));
  1096. // To look if there is a carry
  1097. quotient += roundingBehavior(((int)quotient) & 1,
  1098. sign * (5 + compRem),
  1099. roundingMode);
  1100. }
  1101. // Constructing the result with the appropriate unscaled value
  1102. return valueOf(quotient, scale);
  1103. }
  1104. /**
  1105. * Returns a new {@code BigDecimal} whose value is {@code this / divisor}.
  1106. * The scale of the result is the scale of {@code this}. If rounding is
  1107. * required to meet the specified scale, then the specified rounding mode
  1108. * {@code roundingMode} is applied.
  1109. *
  1110. * @param divisor
  1111. * value by which {@code this} is divided.
  1112. * @param roundingMode
  1113. * rounding mode to be used to round the result.
  1114. * @return {@code this / divisor} rounded according to the given rounding
  1115. * mode.
  1116. * @throws NullPointerException
  1117. * if {@code divisor == null}.
  1118. * @throws IllegalArgumentException
  1119. * if {@code roundingMode} is not a valid rounding mode.
  1120. * @throws ArithmeticException
  1121. * if {@code divisor == 0}.
  1122. * @throws ArithmeticException
  1123. * if {@code roundingMode == ROUND_UNNECESSARY} and rounding is
  1124. * necessary according to the scale of this.
  1125. */
  1126. public BigDecimal divide(BigDecimal divisor, int roundingMode) {
  1127. return divide(divisor, scaleJ, RoundingMode.valueOf(roundingMode));
  1128. }
  1129. /**
  1130. * Returns a new {@code BigDecimal} whose value is {@code this / divisor}.
  1131. * The scale of the result is the scale of {@code this}. If rounding is
  1132. * required to meet the specified scale, then the specified rounding mode
  1133. * {@code roundingMode} is applied.
  1134. *
  1135. * @param divisor
  1136. * value by which {@code this} is divided.
  1137. * @param roundingMode
  1138. * rounding mode to be used to round the result.
  1139. * @return {@code this / divisor} rounded according to the given rounding
  1140. * mode.
  1141. * @throws NullPointerException
  1142. * if {@code divisor == null} or {@code roundingMode == null}.
  1143. * @throws ArithmeticException
  1144. * if {@code divisor == 0}.
  1145. * @throws ArithmeticException
  1146. * if {@code roundingMode == RoundingMode.UNNECESSARY} and
  1147. * rounding is necessary according to the scale of this.
  1148. */
  1149. public BigDecimal divide(BigDecimal divisor, RoundingMode roundingMode) {
  1150. return divide(divisor, scaleJ, roundingMode);
  1151. }
  1152. /**
  1153. * Returns a new {@code BigDecimal} whose value is {@code this / divisor}.
  1154. * The scale of the result is the difference of the scales of {@code this}
  1155. * and {@code divisor}. If the exact result requires more digits, then the
  1156. * scale is adjusted accordingly. For example, {@code 1/128 = 0.0078125}
  1157. * which has a scale of {@code 7} and precision {@code 5}.
  1158. *
  1159. * @param divisor
  1160. * value by which {@code this} is divided.
  1161. * @return {@code this / divisor}.
  1162. * @throws NullPointerException
  1163. * if {@code divisor == null}.
  1164. * @throws ArithmeticException
  1165. * if {@code divisor == 0}.
  1166. * @throws ArithmeticException
  1167. * if the result cannot be represented exactly.
  1168. */
  1169. public BigDecimal divide(BigDecimal divisor) {
  1170. BigInteger p = this.getUnscaledValue();
  1171. BigInteger q = divisor.getUnscaledValue();
  1172. BigInteger gcd; // greatest common divisor between 'p' and 'q'
  1173. BigInteger[] quotAndRem;
  1174. long diffScale = (long)scaleJ - divisor.scaleJ;
  1175. int newScale; // the new scale for final quotient
  1176. int k; // number of factors "2" in 'q'
  1177. int l = 0; // number of factors "5" in 'q'
  1178. int i = 1;
  1179. int lastPow = FIVE_POW.Length - 1;
  1180. if (divisor.isZero()) {
  1181. // math.04=Division by zero
  1182. throw new ArithmeticException("Division by zero"); //$NON-NLS-1$
  1183. }
  1184. if (p.signum() == 0) {
  1185. return zeroScaledBy(diffScale);
  1186. }
  1187. // To divide both by the GCD
  1188. gcd = p.gcd(q);
  1189. p = p.divide(gcd);
  1190. q = q.divide(gcd);
  1191. // To simplify all "2" factors of q, dividing by 2^k
  1192. k = q.getLowestSetBit();
  1193. q = q.shiftRight(k);
  1194. // To simplify all "5" factors of q, dividing by 5^l
  1195. do {
  1196. quotAndRem = q.divideAndRemainder(FIVE_POW[i]);
  1197. if (quotAndRem[1].signum() == 0) {
  1198. l += i;
  1199. if (i < lastPow) {
  1200. i++;
  1201. }
  1202. q = quotAndRem[0];
  1203. } else {
  1204. if (i == 1) {
  1205. break;
  1206. }
  1207. i = 1;
  1208. }
  1209. } while (true);
  1210. // If abs(q) != 1 then the quotient is periodic
  1211. if (!q.abs().equals(BigInteger.ONE)) {
  1212. // math.05=Non-terminating decimal expansion; no exact representable decimal result.
  1213. throw new ArithmeticException("Non-terminating decimal expansion; no exact representable decimal result."); //$NON-NLS-1$
  1214. }
  1215. // The sign of the is fixed and the quotient will be saved in 'p'
  1216. if (q.signum() < 0) {
  1217. p = p.negate();
  1218. }
  1219. // Checking if the new scale is out of range
  1220. newScale = toIntScale(diffScale + java.lang.Math.max(k, l));
  1221. // k >= 0 and l >= 0 implies that k - l is in the 32-bit range
  1222. i = k - l;
  1223. p = (i > 0) ? Multiplication.multiplyByFivePow(p, i)
  1224. : p.shiftLeft(-i);
  1225. return new BigDecimal(p, newScale);
  1226. }
  1227. /**
  1228. * Returns a new {@code BigDecimal} whose value is {@code this / divisor}.
  1229. * The result is rounded according to the passed context {@code mc}. If the
  1230. * passed math context specifies precision {@code 0}, then this call is
  1231. * equivalent to {@code this.divide(divisor)}.
  1232. *
  1233. * @param divisor
  1234. * value by which {@code this} is divided.
  1235. * @param mc
  1236. * rounding mode and precision for the result of this operation.
  1237. * @return {@code this / divisor}.
  1238. * @throws NullPointerException
  1239. * if {@code divisor == null} or {@code mc == null}.
  1240. * @throws ArithmeticException
  1241. * if {@code divisor == 0}.
  1242. * @throws ArithmeticException
  1243. * if {@code mc.getRoundingMode() == UNNECESSARY} and rounding
  1244. * is necessary according {@code mc.getPrecision()}.
  1245. */
  1246. public BigDecimal divide(BigDecimal divisor, MathContext mc) {
  1247. /* Calculating how many zeros must be append to 'dividend'
  1248. * to obtain a quotient with at least 'mc.precision()' digits */
  1249. long traillingZeros = mc.getPrecision() + 2L
  1250. + divisor.aproxPrecision() - aproxPrecision();
  1251. long diffScale = (long)scaleJ - divisor.scaleJ;
  1252. long newScale = diffScale; // scale of the final quotient
  1253. int compRem; // to compare the remainder
  1254. int i = 1; // index
  1255. int lastPow = TEN_POW.Length - 1; // last power of ten
  1256. BigInteger integerQuot; // for temporal results
  1257. BigInteger []quotAndRem = {getUnscaledValue()};
  1258. // In special cases it reduces the problem to call the dual method
  1259. if ((mc.getPrecision() == 0) || (this.isZero())
  1260. || (divisor.isZero())) {
  1261. return this.divide(divisor);
  1262. }
  1263. if (traillingZeros > 0) {
  1264. // To append trailing zeros at end of dividend
  1265. quotAndRem[0] = getUnscaledValue().multiply( Multiplication.powerOf10(traillingZeros) );
  1266. newScale += traillingZeros;
  1267. }
  1268. quotAndRem = quotAndRem[0].divideAndRemainder( divisor.getUnscaledValue() );
  1269. integerQuot = quotAndRem[0];
  1270. // Calculating the exact quotient with at least 'mc.precision()' digits
  1271. if (quotAndRem[1].signum() != 0) {
  1272. // Checking if: 2 * remainder >= divisor ?
  1273. compRem = quotAndRem[1].shiftLeftOneBit().compareTo( divisor.getUnscaledValue() );
  1274. // quot := quot * 10 + r; with 'r' in {-6,-5,-4, 0,+4,+5,+6}
  1275. integerQuot = integerQuot.multiply(BigInteger.TEN)
  1276. .add(BigInteger.valueOf(quotAndRem[0].signum() * (5 + compRem)));
  1277. newScale++;
  1278. } else {
  1279. // To strip trailing zeros until the preferred scale is reached
  1280. while (!integerQuot.testBit(0)) {
  1281. quotAndRem = integerQuot.divideAndRemainder(TEN_POW[i]);
  1282. if ((quotAndRem[1].signum() == 0)
  1283. && (newScale - i >= diffScale)) {
  1284. newScale -= i;
  1285. if (i < lastPow) {
  1286. i++;
  1287. }
  1288. integerQuot = quotAndRem[0];
  1289. } else {
  1290. if (i == 1) {
  1291. break;
  1292. }
  1293. i = 1;
  1294. }
  1295. }
  1296. }
  1297. // To perform rounding
  1298. return new BigDecimal(integerQuot, toIntScale(newScale), mc);
  1299. }
  1300. /**
  1301. * Returns a new {@code BigDecimal} whose value is the integral part of
  1302. * {@code this / divisor}. The quotient is rounded down towards zero to the
  1303. * next integer. For example, {@code 0.5/0.2 = 2}.
  1304. *
  1305. * @param divisor
  1306. * value by which {@code this} is divided.
  1307. * @return integral part of {@code this / divisor}.
  1308. * @throws NullPointerException
  1309. * if {@code divisor == null}.
  1310. * @throws ArithmeticException
  1311. * if {@code divisor == 0}.
  1312. */
  1313. public BigDecimal divideToIntegralValue(BigDecimal divisor) {
  1314. BigInteger integralValue; // the integer of result
  1315. BigInteger powerOfTen; // some power of ten
  1316. BigInteger[] quotAndRem = {getUnscaledValue()};
  1317. long newScale = (long)this.scaleJ - divisor.scaleJ;
  1318. long tempScale = 0;
  1319. int i = 1;
  1320. int lastPow = TEN_POW.Length - 1;
  1321. if (divisor.isZero()) {
  1322. // math.04=Division by zero
  1323. throw new ArithmeticException("Division by zero"); //$NON-NLS-1$
  1324. }
  1325. if ((divisor.aproxPrecision() + newScale > this.aproxPrecision() + 1L)
  1326. || (this.isZero())) {
  1327. /* If the divisor's integer part is greater than this's integer part,
  1328. * the result must be zero with the appropriate scale */
  1329. integralValue = BigInteger.ZERO;
  1330. } else if (newScale == 0) {
  1331. integralValue = getUnscaledValue().divide( divisor.getUnscaledValue() );
  1332. } else if (newScale > 0) {
  1333. powerOfTen = Multiplication.powerOf10(newScale);
  1334. integralValue = getUnscaledValue().divide( divisor.getUnscaledValue().multiply(powerOfTen) );
  1335. integralValue = integralValue.multiply(powerOfTen);
  1336. } else {// (newScale < 0)
  1337. powerOfTen = Multiplication.powerOf10(-newScale);
  1338. integralValue = getUnscaledValue().multiply(powerOfTen).divide( divisor.getUnscaledValue() );
  1339. // To strip trailing zeros approximating to the preferred scale
  1340. while (!integralValue.testBit(0)) {
  1341. quotAndRem = integralValue.divideAndRemainder(TEN_POW[i]);
  1342. if ((quotAndRem[1].signum() == 0)
  1343. && (tempScale - i >= newScale)) {
  1344. tempScale -= i;
  1345. if (i < lastPow) {
  1346. i++;
  1347. }
  1348. integralValue = quotAndRem[0];
  1349. } else {
  1350. if (i == 1) {
  1351. break;
  1352. }
  1353. i = 1;
  1354. }
  1355. }
  1356. newScale = tempScale;
  1357. }
  1358. return ((integralValue.signum() == 0)
  1359. ? zeroScaledBy(newScale)
  1360. : new BigDecimal(integralValue, toIntScale(newScale)));
  1361. }
  1362. /**
  1363. * Returns a new {@code BigDecimal} whose value is the integral part of
  1364. * {@code this / divisor}. The quotient is rounded down towards zero to the
  1365. * next integer. The rounding mode passed with the parameter {@code mc} is
  1366. * not considered. But if the precision of {@code mc > 0} and the integral
  1367. * part requires more digits, then an {@code ArithmeticException} is thrown.
  1368. *
  1369. * @param divisor
  1370. * value by which {@code this} is divided.
  1371. * @param mc
  1372. * math context which determines the maximal precision of the
  1373. * result.
  1374. * @return integral part of {@code this / divisor}.
  1375. * @throws NullPointerException
  1376. * if {@code divisor == null} or {@code mc == null}.
  1377. * @throws ArithmeticException
  1378. * if {@code divisor == 0}.
  1379. * @throws ArithmeticException
  1380. * if {@code mc.getPrecision() > 0} and the result requires more
  1381. * digits to be represented.
  1382. */
  1383. public BigDecimal divideToIntegralValue(BigDecimal divisor, MathContext mc) {
  1384. int mcPrecision = mc.getPrecision();
  1385. int diffPrecision = this.precision() - divisor.precision();
  1386. int lastPow = TEN_POW.Length - 1;
  1387. long diffScale = (long)this.scaleJ - divisor.scaleJ;
  1388. long newScale = diffScale;
  1389. long quotPrecision = diffPrecision - diffScale + 1;
  1390. BigInteger []quotAndRem = new BigInteger[2];
  1391. // In special cases it call the dual method
  1392. if ((mcPrecision == 0) || (this.isZero()) || (divisor.isZero())) {
  1393. return this.divideToIntegralValue(divisor);
  1394. }
  1395. // Let be: this = [u1,s1] and divisor = [u2,s2]
  1396. if (quotPrecision <= 0) {
  1397. quotAndRem[0] = BigInteger.ZERO;
  1398. } else if (diffScale == 0) {
  1399. // CASE s1 == s2: to calculate u1 / u2
  1400. quotAndRem[0] = this.getUnscaledValue().divide( divisor.getUnscaledValue() );
  1401. } else if (diffScale > 0) {
  1402. // CASE s1 >= s2: to calculate u1 / (u2 * 10^(s1-s2)
  1403. quotAndRem[0] = this.getUnscaledValue().divide(
  1404. divisor.getUnscaledValue().multiply(Multiplication.powerOf10(diffScale)) );
  1405. // To chose 10^newScale to get a quotient with at least 'mc.precision()' digits
  1406. newScale = java.lang.Math.min(diffScale, java.lang.Math.max(mcPrecision - quotPrecision + 1, 0));
  1407. // To calculate: (u1 / (u2 * 10^(s1-s2)) * 10^newScale
  1408. quotAndRem[0] = quotAndRem[0].multiply(Multiplication.powerOf10(newScale));
  1409. } else {// CASE s2 > s1:
  1410. /* To calculate the minimum power of ten, such that the quotient
  1411. * (u1 * 10^exp) / u2 has at least 'mc.precision()' digits. */
  1412. long exp = java.lang.Math.min(-diffScale, java.lang.Math.max((long)mcPrecision - diffPrecision, 0));
  1413. long compRemDiv;
  1414. // Let be: (u1 * 10^exp) / u2 = [q,r]
  1415. quotAndRem = this.getUnscaledValue().multiply(Multiplication.powerOf10(exp)).
  1416. divideAndRemainder(divisor.getUnscaledValue());
  1417. newScale += exp; // To fix the scale
  1418. exp = -newScale; // The remaining power of ten
  1419. // If after division there is a remainder...
  1420. if ((quotAndRem[1].signum() != 0) && (exp > 0)) {
  1421. // Log10(r) + ((s2 - s1) - exp) > mc.precision ?
  1422. compRemDiv = (new BigDecimal(quotAndRem[1])).precision()
  1423. + exp - divisor.precision();
  1424. if (compRemDiv == 0) {
  1425. // To calculate: (r * 10^exp2) / u2
  1426. quotAndRem[1] = quotAndRem[1].multiply(Multiplication.powerOf10(exp)).
  1427. divide(divisor.getUnscaledValue());
  1428. compRemDiv = java.lang.Math.abs(quotAndRem[1].signum());
  1429. }
  1430. if (compRemDiv > 0) {
  1431. // The quotient won't fit in 'mc.precision()' digits
  1432. // math.06=Division impossible
  1433. throw new java.lang.ArithmeticException("Division impossible"); //$NON-NLS-1$
  1434. }
  1435. }
  1436. }
  1437. // Fast return if the quotient is zero
  1438. if (quotAndRem[0].signum() == 0) {
  1439. return zeroScaledBy(diffScale);
  1440. }
  1441. BigInteger strippedBI = quotAndRem[0];
  1442. BigDecimal integralValue = new BigDecimal(quotAndRem[0]);
  1443. long resultPrecision = integralValue.precision();
  1444. int i = 1;
  1445. // To strip trailing zeros until the specified precision is reached
  1446. while (!strippedBI.testBit(0)) {
  1447. quotAndRem = strippedBI.divideAndRemainder(TEN_POW[i]);
  1448. if ((quotAndRem[1].signum() == 0) &&
  1449. ((resultPrecision - i >= mcPrecision)
  1450. || (newScale - i >= diffScale)) ) {
  1451. resultPrecision -= i;
  1452. newScale -= i;
  1453. if (i < lastPow) {
  1454. i++;
  1455. }
  1456. strippedBI = quotAndRem[0];
  1457. } else {
  1458. if (i == 1) {
  1459. break;
  1460. }
  1461. i = 1;
  1462. }
  1463. }
  1464. // To check if the result fit in 'mc.precision()' digits
  1465. if (resultPrecision > mcPrecision) {
  1466. // math.06=Division impossible
  1467. throw new java.lang.ArithmeticException("Division impossible"); //$NON-NLS-1$
  1468. }
  1469. integralValue.scaleJ = toIntScale(newScale);
  1470. integralValue.setUnscaledValue(strippedBI);
  1471. return integralValue;
  1472. }
  1473. /**
  1474. * Returns a new {@code BigDecimal} whose value is {@code this % divisor}.
  1475. * <p>
  1476. * The remainder is defined as {@code this -
  1477. * this.divideToIntegralValue(divisor) * divisor}.
  1478. *
  1479. * @param divisor
  1480. * value by which {@code this} is divided.
  1481. * @return {@code this % divisor}.
  1482. * @throws NullPointerException
  1483. * if {@code divisor == null}.
  1484. * @throws ArithmeticException
  1485. * if {@code divisor == 0}.
  1486. */
  1487. public BigDecimal remainder(BigDecimal divisor) {
  1488. return divideAndRemainder(divisor)[1];
  1489. }
  1490. /**
  1491. * Returns a new {@code BigDecimal} whose value is {@code this % divisor}.
  1492. * <p>
  1493. * The remainder is defined as {@code this -
  1494. * this.divideToIntegralValue(divisor) * divisor}.
  1495. * <p>
  1496. * The specified rounding mode {@code mc} is used for the division only.
  1497. *
  1498. * @param divisor
  1499. * value by which {@code this} is divided.
  1500. * @param mc
  1501. * rounding mode and precision to be used.
  1502. * @return {@code this % divisor}.
  1503. * @throws NullPointerException
  1504. * if {@code divisor == null}.
  1505. * @throws ArithmeticException
  1506. * if {@code divisor == 0}.
  1507. * @throws ArithmeticException
  1508. * if {@code mc.getPrecision() > 0} and the result of {@code
  1509. * this.divideToIntegralValue(divisor, mc)} requires more digits
  1510. * to be represented.
  1511. */
  1512. public BigDecimal remainder(BigDecimal divisor, MathContext mc) {
  1513. return divideAndRemainder(divisor, mc)[1];
  1514. }
  1515. /**
  1516. * Returns a {@code BigDecimal} array which contains the integral part of
  1517. * {@code this / divisor} at index 0 and the remainder {@code this %
  1518. * divisor} at index 1. The quotient is rounded down towards zero to the
  1519. * next integer.
  1520. *
  1521. * @param divisor
  1522. * value by which {@code this} is divided.
  1523. * @return {@code [this.divideToIntegralValue(divisor),
  1524. * this.remainder(divisor)]}.
  1525. * @throws NullPointerException
  1526. * if {@code divisor == null}.
  1527. * @throws ArithmeticException
  1528. * if {@code divisor == 0}.
  1529. * @see #divideToIntegralValue
  1530. * @see #remainder
  1531. */
  1532. public BigDecimal[] divideAndRemainder(BigDecimal divisor) {
  1533. BigDecimal[] quotAndRem = new BigDecimal[2];
  1534. quotAndRem[0] = this.divideToIntegralValue(divisor);
  1535. quotAndRem[1] = this.subtract( quotAndRem[0].multiply(divisor) );
  1536. return quotAndRem;
  1537. }
  1538. /**
  1539. * Returns a {@code BigDecimal} array which contains the integral part of
  1540. * {@code this / divisor} at index 0 and the remainder {@code this %
  1541. * divisor} at index 1. The quotient is rounded down towards zero to the
  1542. * next integer. The rounding mode passed with the parameter {@code mc} is
  1543. * not considered. But if the precision of {@code mc > 0} and the integral
  1544. * part requires more digits, then an {@code ArithmeticException} is thrown.
  1545. *
  1546. * @param divisor
  1547. * value by which {@code this} is divided.
  1548. * @param mc
  1549. * math context which determines the maximal precision of the
  1550. * result.
  1551. * @return {@code [this.divideToIntegralValue(divisor),
  1552. * this.remainder(divisor)]}.
  1553. * @throws NullPointerException
  1554. * if {@code divisor == null}.
  1555. * @throws ArithmeticException
  1556. * if {@code divisor == 0}.
  1557. * @see #divideToIntegralValue
  1558. * @see #remainder
  1559. */
  1560. public BigDecimal[] divideAndRemainder(BigDecimal divisor, MathContext mc) {
  1561. BigDecimal[] quotAndRem = new BigDecimal[2];
  1562. quotAndRem[0] = this.divideToIntegralValue(divisor, mc);
  1563. quotAndRem[1] = this.subtract( quotAndRem[0].multiply(divisor) );
  1564. return quotAndRem;
  1565. }
  1566. /**
  1567. * Returns a new {@code BigDecimal} whose value is {@code this ^ n}. The
  1568. * scale of the result is {@code n} times the scales of {@code this}.
  1569. * <p>
  1570. * {@code x.pow(0)} returns {@code 1}, even if {@code x == 0}.
  1571. * <p>
  1572. * Implementation Note: The implementation is based on the ANSI standard
  1573. * X3.274-1996 algorithm.
  1574. *
  1575. * @param n
  1576. * exponent to which {@code this} is raised.
  1577. * @return {@code this ^ n}.
  1578. * @throws ArithmeticException
  1579. * if {@code n < 0} or {@code n > 999999999}.
  1580. */
  1581. public BigDecimal pow(int n) {
  1582. if (n == 0) {
  1583. return ONE;
  1584. }
  1585. if ((n < 0) || (n > 999999999)) {
  1586. // math.07=Invalid Operation
  1587. throw new ArithmeticException("Invalid Operation"); //$NON-NLS-1$
  1588. }
  1589. long newScale = this.scaleJ * (long)n;
  1590. // Let be: this = [u,s] so: this^n = [u^n, s*n]
  1591. return ((isZero())
  1592. ? zeroScaledBy(newScale)
  1593. : new BigDecimal(getUnscaledValue().pow(n), toIntScale(newScale)));
  1594. }
  1595. /**
  1596. * Returns a new {@code BigDecimal} whose value is {@code this ^ n}. The
  1597. * result is rounded according to the passed context {@code mc}.
  1598. * <p>
  1599. * Implementation Note: The implementation is based on the ANSI standard
  1600. * X3.274-1996 algorithm.
  1601. *
  1602. * @param n
  1603. * exponent to which {@code this} is raised.
  1604. * @param mc
  1605. * rounding mode and precision for the result of this operation.
  1606. * @return {@code this ^ n}.
  1607. * @throws ArithmeticException
  1608. * if {@code n < 0} or {@code n > 999999999}.
  1609. */
  1610. public BigDecimal pow(int n, MathContext mc) {
  1611. // The ANSI standard X3.274-1996 algorithm
  1612. int m = java.lang.Math.abs(n);
  1613. int mcPrecision = mc.getPrecision();
  1614. int elength = (int)java.lang.Math.log10(m) + 1; // decimal digits in 'n'
  1615. int oneBitMask; // mask of bits
  1616. BigDecimal accum; // the single accumulator
  1617. MathContext newPrecision = mc; // MathContext by default
  1618. // In particular cases, it reduces the problem to call the other 'pow()'
  1619. if ((n == 0) || ((isZero()) && (n > 0))) {
  1620. return pow(n);
  1621. }
  1622. if ((m > 999999999) || ((mcPrecision == 0) && (n < 0))
  1623. || ((mcPrecision > 0) && (elength > mcPrecision))) {
  1624. // math.07=Invalid Operation
  1625. throw new ArithmeticException("Invalid Operation"); //$NON-NLS-1$
  1626. }
  1627. if (mcPrecision > 0) {
  1628. newPrecision = new MathContext( mcPrecision + elength + 1,
  1629. mc.getRoundingMode());
  1630. }
  1631. // The result is calculated as if 'n' were positive
  1632. accum = round(newPrecision);
  1633. oneBitMask = java.lang.Integer.highestOneBit(m) >> 1;
  1634. while (oneBitMask > 0) {
  1635. accum = accum.multiply(accum, newPrecision);
  1636. if ((m & oneBitMask) == oneBitMask) {
  1637. accum = accum.multiply(this, newPrecision);
  1638. }
  1639. oneBitMask >>= 1;
  1640. }
  1641. // If 'n' is negative, the value is divided into 'ONE'
  1642. if (n < 0) {
  1643. accum = ONE.divide(accum, newPrecision);
  1644. }
  1645. // The final value is rounded to the destination precision
  1646. accum.inplaceRound(mc);
  1647. return accum;
  1648. }
  1649. /**
  1650. * Returns a new {@code BigDecimal} whose value is the absolute value of
  1651. * {@code this}. The scale of the result is the same as the scale of this.
  1652. *
  1653. * @return {@code abs(this)}
  1654. */
  1655. public BigDecimal abs() {
  1656. return ((signum() < 0) ? negate() : this);
  1657. }
  1658. /**
  1659. * Returns a new {@code BigDecimal} whose value is the absolute value of
  1660. * {@code this}. The result is rounded according to the passed context
  1661. * {@code mc}.
  1662. *
  1663. * @param mc
  1664. * rounding mode and precision for the result of this operation.
  1665. * @return {@code abs(this)}
  1666. */
  1667. public BigDecimal abs(MathContext mc) {
  1668. return round(mc).abs();
  1669. }
  1670. /**
  1671. * Returns a new {@code BigDecimal} whose value is the {@code -this}. The
  1672. * scale of the result is the same as the scale of this.
  1673. *
  1674. * @return {@code -this}
  1675. */
  1676. public BigDecimal negate() {
  1677. if(bitLengthJ < 63 || (bitLengthJ == 63 && smallValue!=java.lang.Long.MIN_VALUE)) {
  1678. return valueOf(-smallValue,scaleJ);
  1679. }
  1680. return new BigDecimal(getUnscaledValue().negate(), scaleJ);
  1681. }
  1682. /**
  1683. * Returns a new {@code BigDecimal} whose value is the {@code -this}. The
  1684. * result is rounded according to the passed context {@code mc}.
  1685. *
  1686. * @param mc
  1687. * rounding mode and precision for the result of this operation.
  1688. * @return {@code -this}
  1689. */
  1690. public BigDecimal negate(MathContext mc) {
  1691. return round(mc).negate();
  1692. }
  1693. /**
  1694. * Returns a new {@code BigDecimal} whose value is {@code +this}. The scale
  1695. * of the result is the same as the scale of this.
  1696. *
  1697. * @return {@code this}
  1698. */
  1699. public BigDecimal plus() {
  1700. return this;
  1701. }
  1702. /**
  1703. * Returns a new {@code BigDecimal} whose value is {@code +this}. The result
  1704. * is rounded according to the passed context {@code mc}.
  1705. *
  1706. * @param mc
  1707. * rounding mode and precision for the result of this operation.
  1708. * @return {@code this}, rounded
  1709. */
  1710. public BigDecimal plus(MathContext mc) {
  1711. return round(mc);
  1712. }
  1713. /**
  1714. * Returns the sign of this {@code BigDecimal}.
  1715. *
  1716. * @return {@code -1} if {@code this < 0},
  1717. * {@code 0} if {@code this == 0},
  1718. * {@code 1} if {@code this > 0}. */
  1719. public virtual int signum() {
  1720. if( bitLengthJ < 64) {
  1721. return java.lang.Long.signum( this.smallValue );
  1722. }
  1723. return getUnscaledValue().signum();
  1724. }
  1725. private bool isZero() {
  1726. //Watch out: -1 has a bitLengthJ=0
  1727. return bitLengthJ == 0 && this.smallValue != -1;
  1728. }
  1729. /**
  1730. * Returns the scale of this {@code BigDecimal}. The scale is the number of
  1731. * digits behind the decimal point. The value of this {@code BigDecimal} is
  1732. * the unsignedValue * 10^(-scale). If the scale is negative, then this
  1733. * {@code BigDecimal} represents a big integer.
  1734. *
  1735. * @return the scale of this {@code BigDecimal}.
  1736. */
  1737. public virtual int scale() {
  1738. return scaleJ;
  1739. }
  1740. /**
  1741. * Returns the precision of this {@code BigDecimal}. The precision is the
  1742. * number of decimal digits used to represent this decimal. It is equivalent
  1743. * to the number of digits of the unscaled value. The precision of {@code 0}
  1744. * is {@code 1} (independent of the scale).
  1745. *
  1746. * @return the precision of this {@code BigDecimal}.
  1747. */
  1748. public int precision() {
  1749. // Checking if the precision already was calculated
  1750. if (precisionJ > 0) {
  1751. return precisionJ;
  1752. }
  1753. int bitLengthJ = this.bitLengthJ;
  1754. int decimalDigits = 1; // the precision to be calculated
  1755. double doubleUnsc = 1; // intVal in 'double'
  1756. if (bitLengthJ < 1024) {
  1757. // To calculate the precision for small numbers
  1758. if (bitLengthJ >= 64) {
  1759. doubleUnsc = getUnscaledValue().doubleValue();
  1760. } else if (bitLengthJ >= 1) {
  1761. doubleUnsc = smallValue;
  1762. }
  1763. decimalDigits = (int) (decimalDigits+ java.lang.Math.log10(java.lang.Math.abs(doubleUnsc)));
  1764. } else {// (bitLengthJ >= 1024)
  1765. /* To calculate the precision for large numbers
  1766. * Note that: 2 ^(bitLengthJ() - 1) <= intVal < 10 ^(precision()) */
  1767. decimalDigits = (int)(decimalDigits+ ((bitLengthJ - 1) * LOG10_2));
  1768. // If after division the number isn't zero, exists an aditional digit
  1769. if (getUnscaledValue().divide(Multiplication.powerOf10(decimalDigits)).signum() != 0) {
  1770. decimalDigits++;
  1771. }
  1772. }
  1773. precisionJ = decimalDigits;
  1774. return precisionJ;
  1775. }
  1776. /**
  1777. * Returns the unscaled value (mantissa) of this {@code BigDecimal} instance
  1778. * as a {@code BigInteger}. The unscaled value can be computed as {@code
  1779. * this} 10^(scale).
  1780. *
  1781. * @return unscaled value (this * 10^(scale)).
  1782. */
  1783. public BigInteger unscaledValue() {
  1784. return getUnscaledValue();
  1785. }
  1786. /**
  1787. * Returns a new {@code BigDecimal} whose value is {@code this}, rounded
  1788. * according to the passed context {@code mc}.
  1789. * <p>
  1790. * If {@code mc.precision = 0}, then no rounding is performed.
  1791. * <p>
  1792. * If {@code mc.precision > 0} and {@code mc.roundingMode == UNNECESSARY},
  1793. * then an {@code ArithmeticException} is thrown if the result cannot be
  1794. * represented exactly within the given precision.
  1795. *
  1796. * @param mc
  1797. * rounding mode and precision for the result of this operation.
  1798. * @return {@code this} rounded according to the passed context.
  1799. * @throws ArithmeticException
  1800. * if {@code mc.precision > 0} and {@code mc.roundingMode ==
  1801. * UNNECESSARY} and this cannot be represented within the given
  1802. * precision.
  1803. */
  1804. public BigDecimal round(MathContext mc) {
  1805. BigDecimal thisBD = new BigDecimal(getUnscaledValue(), scaleJ);
  1806. thisBD.inplaceRound(mc);
  1807. return thisBD;
  1808. }
  1809. /**
  1810. * Returns a new {@code BigDecimal} instance with the specified scale.
  1811. * <p>
  1812. * If the new scale is greater than the old scale, then additional zeros are
  1813. * added to the unscaled value. In this case no rounding is necessary.
  1814. * <p>
  1815. * If the new scale is smaller than the old scale, then trailing digits are
  1816. * removed. If these trailing digits are not zero, then the remaining
  1817. * unscaled value has to be rounded. For this rounding operation the
  1818. * specified rounding mode is used.
  1819. *
  1820. * @param newScale
  1821. * scale of the result returned.
  1822. * @param roundingMode
  1823. * rounding mode to be used to round the result.
  1824. * @return a new {@code BigDecimal} instance with the specified scale.
  1825. * @throws NullPointerException
  1826. * if {@code roundingMode == null}.
  1827. * @throws ArithmeticException
  1828. * if {@code roundingMode == ROUND_UNNECESSARY} and rounding is
  1829. * necessary according to the given scale.
  1830. */
  1831. public BigDecimal setScale(int newScale, RoundingMode roundingMode) {
  1832. if (roundingMode == null) {
  1833. throw new java.lang.NullPointerException();
  1834. }
  1835. long diffScale = newScale - (long)scaleJ;
  1836. // Let be: 'this' = [u,s]
  1837. if(diffScale == 0) {
  1838. return this;
  1839. }
  1840. if(diffScale > 0) {
  1841. // return [u * 10^(s2 - s), newScale]
  1842. if(diffScale < LONG_TEN_POW.Length &&
  1843. (this.bitLengthJ + LONG_TEN_POW_BIT_LENGTH[(int)diffScale]) < 64 ) {
  1844. return valueOf(this.smallValue*LONG_TEN_POW[(int)diffScale],newScale);
  1845. }
  1846. return new BigDecimal(Multiplication.multiplyByTenPow(getUnscaledValue(),(int)diffScale), newScale);
  1847. }
  1848. // diffScale < 0
  1849. // return [u,s] / [1,newScale] with the appropriate scale and rounding
  1850. if(this.bitLengthJ < 64 && -diffScale < LONG_TEN_POW.Length) {
  1851. return dividePrimitiveLongs(this.smallValue, LONG_TEN_POW[(int)-diffScale], newScale,roundingMode);
  1852. }
  1853. return divideBigIntegers(this.getUnscaledValue(),Multiplication.powerOf10(-diffScale),newScale,roundingMode);
  1854. }
  1855. /**
  1856. * Returns a new {@code BigDecimal} instance with the specified scale.
  1857. * <p>
  1858. * If the new scale is greater than the old scale, then additional zeros are
  1859. * added to the unscaled value. In this case no rounding is necessary.
  1860. * <p>
  1861. * If the new scale is smaller than the old scale, then trailing digits are
  1862. * removed. If these trailing digits are not zero, then the remaining
  1863. * unscaled value has to be rounded. For this rounding operation the
  1864. * specified rounding mode is used.
  1865. *
  1866. * @param newScale
  1867. * scale of the result returned.
  1868. * @param roundingMode
  1869. * rounding mode to be used to round the result.
  1870. * @return a new {@code BigDecimal} instance with the specified scale.
  1871. * @throws IllegalArgumentException
  1872. * if {@code roundingMode} is not a valid rounding mode.
  1873. * @throws ArithmeticException
  1874. * if {@code roundingMode == ROUND_UNNECESSARY} and rounding is
  1875. * necessary according to the given scale.
  1876. */
  1877. public BigDecimal setScale(int newScale, int roundingMode) {
  1878. return setScale(newScale, RoundingMode.valueOf(roundingMode));
  1879. }
  1880. /**
  1881. * Returns a new {@code BigDecimal} instance with the specified scale. If
  1882. * the new scale is greater than the old scale, then additional zeros are
  1883. * added to the unscaled value. If the new scale is smaller than the old
  1884. * scale, then trailing zeros are removed. If the trailing digits are not
  1885. * zeros then an ArithmeticException is thrown.
  1886. * <p>
  1887. * If no exception is thrown, then the following equation holds: {@code
  1888. * x.setScale(s).compareTo(x) == 0}.
  1889. *
  1890. * @param newScale
  1891. * scale of the result returned.
  1892. * @return a new {@code BigDecimal} instance with the specified scale.
  1893. * @throws ArithmeticException
  1894. * if rounding would be necessary.
  1895. */
  1896. public BigDecimal setScale(int newScale) {
  1897. return setScale(newScale, RoundingMode.UNNECESSARY);
  1898. }
  1899. /**
  1900. * Returns a new {@code BigDecimal} instance where the decimal point has
  1901. * been moved {@code n} places to the left. If {@code n < 0} then the
  1902. * decimal point is moved {@code -n} places to the right.
  1903. * <p>
  1904. * The result is obtained by changing its scale. If the scale of the result
  1905. * becomes negative, then its precision is increased such that the scale is
  1906. * zero.
  1907. * <p>
  1908. * Note, that {@code movePointLeft(0)} returns a result which is
  1909. * mathematically equivalent, but which has {@code scale >= 0}.
  1910. *
  1911. * @param n
  1912. * number of placed the decimal point has to be moved.
  1913. * @return {@code this * 10^(-n}).
  1914. */
  1915. public virtual BigDecimal movePointLeft(int n) {
  1916. return movePoint(scaleJ + (long)n);
  1917. }
  1918. private BigDecimal movePoint(long newScale) {
  1919. if (isZero()) {
  1920. return zeroScaledBy(java.lang.Math.max(newScale, 0));
  1921. }
  1922. /* When: 'n'== Integer.MIN_VALUE isn't possible to call to movePointRight(-n)
  1923. * since -Integer.MIN_VALUE == Integer.MIN_VALUE */
  1924. if(newScale >= 0) {
  1925. if(bitLengthJ < 64) {
  1926. return valueOf(smallValue,toIntScale(newScale));
  1927. }
  1928. return new BigDecimal(getUnscaledValue(), toIntScale(newScale));
  1929. }
  1930. if(-newScale < LONG_TEN_POW.Length &&
  1931. bitLengthJ + LONG_TEN_POW_BIT_LENGTH[(int)-newScale] < 64 ) {
  1932. return valueOf(smallValue*LONG_TEN_POW[(int)-newScale],0);
  1933. }
  1934. return new BigDecimal(Multiplication.multiplyByTenPow(getUnscaledValue(),(int)-newScale), 0);
  1935. }
  1936. /**
  1937. * Returns a new {@code BigDecimal} instance where the decimal point has
  1938. * been moved {@code n} places to the right. If {@code n < 0} then the
  1939. * decimal point is moved {@code -n} places to the left.
  1940. * <p>
  1941. * The result is obtained by changing its scale. If the scale of the result
  1942. * becomes negative, then its precision is increased such that the scale is
  1943. * zero.
  1944. * <p>
  1945. * Note, that {@code movePointRight(0)} returns a result which is
  1946. * mathematically equivalent, but which has scale >= 0.
  1947. *
  1948. * @param n
  1949. * number of placed the decimal point has to be moved.
  1950. * @return {@code this * 10^n}.
  1951. */
  1952. public BigDecimal movePointRight(int n) {
  1953. return movePoint(scaleJ - (long)n);
  1954. }
  1955. /**
  1956. * Returns a new {@code BigDecimal} whose value is {@code this} 10^{@code n}.
  1957. * The scale of the result is {@code this.scale()} - {@code n}.
  1958. * The precision of the result is the precision of {@code this}.
  1959. * <p>
  1960. * This method has the same effect as {@link #movePointRight}, except that
  1961. * the precision is not changed.
  1962. *
  1963. * @param n
  1964. * number of places the decimal point has to be moved.
  1965. * @return {@code this * 10^n}
  1966. */
  1967. public BigDecimal scaleByPowerOfTen(int n) {
  1968. long newScale = scaleJ - (long)n;
  1969. if(bitLengthJ < 64) {
  1970. //Taking care when a 0 is to be scaled
  1971. if( smallValue==0 ){
  1972. return zeroScaledBy( newScale );
  1973. }
  1974. return valueOf(smallValue,toIntScale(newScale));
  1975. }
  1976. return new BigDecimal(getUnscaledValue(), toIntScale(newScale));
  1977. }
  1978. /**
  1979. * Returns a new {@code BigDecimal} instance with the same value as {@code
  1980. * this} but with a unscaled value where the trailing zeros have been
  1981. * removed. If the unscaled value of {@code this} has n trailing zeros, then
  1982. * the scale and the precision of the result has been reduced by n.
  1983. *
  1984. * @return a new {@code BigDecimal} instance equivalent to this where the
  1985. * trailing zeros of the unscaled value have been removed.
  1986. */
  1987. public BigDecimal stripTrailingZeros() {
  1988. int i = 1; // 1 <= i <= 18
  1989. int lastPow = TEN_POW.Length - 1;
  1990. long newScale = scaleJ;
  1991. if (isZero()) {
  1992. return new BigDecimal("0");
  1993. }
  1994. BigInteger strippedBI = getUnscaledValue();
  1995. BigInteger[] quotAndRem;
  1996. // while the number is even...
  1997. while (!strippedBI.testBit(0)) {
  1998. // To divide by 10^i
  1999. quotAndRem = strippedBI.divideAndRemainder(TEN_POW[i]);
  2000. // To look the remainder
  2001. if (quotAndRem[1].signum() == 0) {
  2002. // To adjust the scale
  2003. newScale -= i;
  2004. if (i < lastPow) {
  2005. // To set to the next power
  2006. i++;
  2007. }
  2008. strippedBI = quotAndRem[0];
  2009. } else {
  2010. if (i == 1) {
  2011. // 'this' has no more trailing zeros
  2012. break;
  2013. }
  2014. // To set to the smallest power of ten
  2015. i = 1;
  2016. }
  2017. }
  2018. return new BigDecimal(strippedBI, toIntScale(newScale));
  2019. }
  2020. /**
  2021. * Compares this {@code BigDecimal} with {@code val}. Returns one of the
  2022. * three values {@code 1}, {@code 0}, or {@code -1}. The method behaves as
  2023. * if {@code this.subtract(val)} is computed. If this difference is > 0 then
  2024. * 1 is returned, if the difference is < 0 then -1 is returned, and if the
  2025. * difference is 0 then 0 is returned. This means, that if two decimal
  2026. * instances are compared which are equal in value but differ in scale, then
  2027. * these two instances are considered as equal.
  2028. *
  2029. * @param val
  2030. * value to be compared with {@code this}.
  2031. * @return {@code 1} if {@code this > val}, {@code -1} if {@code this < val},
  2032. * {@code 0} if {@code this == val}.
  2033. * @throws NullPointerException
  2034. * if {@code val == null}.
  2035. */
  2036. public int compareTo(BigDecimal val) {
  2037. int thisSign = signum();
  2038. int valueSign = val.signum();
  2039. if( thisSign == valueSign) {
  2040. if(this.scaleJ == val.scaleJ && this.bitLengthJ<64 && val.bitLengthJ<64 ) {
  2041. return (smallValue < val.smallValue) ? -1 : (smallValue > val.smallValue) ? 1 : 0;
  2042. }
  2043. long diffScale = (long)this.scaleJ - val.scaleJ;
  2044. int diffPrecision = this.aproxPrecision() - val.aproxPrecision();
  2045. if (diffPrecision > diffScale + 1) {
  2046. return thisSign;
  2047. } else if (diffPrecision < diffScale - 1) {
  2048. return -thisSign;
  2049. } else {// thisSign == val.signum() and diffPrecision is aprox. diffScale
  2050. BigInteger thisUnscaled = this.getUnscaledValue();
  2051. BigInteger valUnscaled = val.getUnscaledValue();
  2052. // If any of both precision is bigger, append zeros to the shorter one
  2053. if (diffScale < 0) {
  2054. thisUnscaled = thisUnscaled.multiply(Multiplication.powerOf10(-diffScale));
  2055. } else if (diffScale > 0) {
  2056. valUnscaled = valUnscaled.multiply(Multiplication.powerOf10(diffScale));
  2057. }
  2058. return thisUnscaled.compareTo(valUnscaled);
  2059. }
  2060. } else if (thisSign < valueSign) {
  2061. return -1;
  2062. } else {
  2063. return 1;
  2064. }
  2065. }
  2066. /**
  2067. * Returns {@code true} if {@code x} is a {@code BigDecimal} instance and if
  2068. * this instance is equal to this big decimal. Two big decimals are equal if
  2069. * their unscaled value and their scale is equal. For example, 1.0
  2070. * (10*10^(-1)) is not equal to 1.00 (100*10^(-2)). Similarly, zero
  2071. * instances are not equal if their scale differs.
  2072. *
  2073. * @param x
  2074. * object to be compared with {@code this}.
  2075. * @return true if {@code x} is a {@code BigDecimal} and {@code this == x}.
  2076. */
  2077. public override bool Equals(Object x) {
  2078. if (this == x) {
  2079. return true;
  2080. }
  2081. if (x is BigDecimal) {
  2082. BigDecimal x1 = (BigDecimal) x;
  2083. return x1.scaleJ == scaleJ
  2084. && (bitLengthJ < 64 ? (x1.smallValue == smallValue)
  2085. : intVal.equals(x1.intVal));
  2086. }
  2087. return false;
  2088. }
  2089. /**
  2090. * Returns the minimum of this {@code BigDecimal} and {@code val}.
  2091. *
  2092. * @param val
  2093. * value to be used to compute the minimum with this.
  2094. * @return {@code min(this, val}.
  2095. * @throws NullPointerException
  2096. * if {@code val == null}.
  2097. */
  2098. public BigDecimal min(BigDecimal val) {
  2099. return ((compareTo(val) <= 0) ? this : val);
  2100. }
  2101. /**
  2102. * Returns the maximum of this {@code BigDecimal} and {@code val}.
  2103. *
  2104. * @param val
  2105. * value to be used to compute the maximum with this.
  2106. * @return {@code max(this, val}.
  2107. * @throws NullPointerException
  2108. * if {@code val == null}.
  2109. */
  2110. public BigDecimal max(BigDecimal val) {
  2111. return ((compareTo(val) >= 0) ? this : val);
  2112. }
  2113. /**
  2114. * Returns a hash code for this {@code BigDecimal}.
  2115. *
  2116. * @return hash code for {@code this}.
  2117. */
  2118. public override int GetHashCode() {
  2119. if (hashCode != 0) {
  2120. return hashCode;
  2121. }
  2122. if (bitLengthJ < 64) {
  2123. hashCode = (int)(smallValue & 0xffffffff);
  2124. hashCode = 33 * hashCode + (int)((smallValue >> 32) & 0xffffffff);
  2125. hashCode = 17 * hashCode + scaleJ;
  2126. return hashCode;
  2127. }
  2128. hashCode = 17 * intVal.GetHashCode() + scaleJ;
  2129. return hashCode;
  2130. }
  2131. /**
  2132. * Returns a canonical string representation of this {@code BigDecimal}. If
  2133. * necessary, scientific notation is used. This representation always prints
  2134. * all significant digits of this value.
  2135. * <p>
  2136. * If the scale is negative or if {@code scale - precision >= 6} then
  2137. * scientific notation is used.
  2138. *
  2139. * @return a string representation of {@code this} in scientific notation if
  2140. * necessary.
  2141. */
  2142. public override String ToString() {
  2143. if (toStringImage != null) {
  2144. return toStringImage;
  2145. }
  2146. if(bitLengthJ < 32) {
  2147. toStringImage = Conversion.toDecimalScaledString(smallValue,scaleJ);
  2148. return toStringImage;
  2149. }
  2150. String intString = getUnscaledValue().toString();
  2151. if (scaleJ == 0) {
  2152. return intString;
  2153. }
  2154. int begin = (getUnscaledValue().signum() < 0) ? 2 : 1;
  2155. int end = intString.length();
  2156. long exponent = -(long)scaleJ + end - begin;
  2157. StringBuilder result = new StringBuilder();
  2158. result.Append(intString);
  2159. if ((scaleJ > 0) && (exponent >= -6)) {
  2160. if (exponent >= 0) {
  2161. result.Insert(end - scaleJ, '.');
  2162. } else {
  2163. result.Insert(begin - 1, "0."); //$NON-NLS-1$
  2164. result.Insert(begin + 1, CH_ZEROS, 0, -(int)exponent - 1);
  2165. }
  2166. } else {
  2167. if (end - begin >= 1) {
  2168. result.Insert(begin, '.');
  2169. end++;
  2170. }
  2171. result.Insert(end, 'E');
  2172. if (exponent > 0) {
  2173. result.Insert(++end, '+');
  2174. }
  2175. result.Insert(++end, java.lang.Long.toString(exponent));
  2176. }
  2177. toStringImage = result.ToString();
  2178. return toStringImage;
  2179. }
  2180. /**
  2181. * Returns a string representation of this {@code BigDecimal}. This
  2182. * representation always prints all significant digits of this value.
  2183. * <p>
  2184. * If the scale is negative or if {@code scale - precision >= 6} then
  2185. * engineering notation is used. Engineering notation is similar to the
  2186. * scientific notation except that the exponent is made to be a multiple of
  2187. * 3 such that the integer part is >= 1 and < 1000.
  2188. *
  2189. * @return a string representation of {@code this} in engineering notation
  2190. * if necessary.
  2191. */
  2192. public String toEngineeringString() {
  2193. String intString = getUnscaledValue().toString();
  2194. if (scaleJ == 0) {
  2195. return intString;
  2196. }
  2197. int begin = (getUnscaledValue().signum() < 0) ? 2 : 1;
  2198. int end = intString.length();
  2199. long exponent = -(long)scaleJ + end - begin;
  2200. StringBuilder result = new StringBuilder(intString);
  2201. if ((scaleJ > 0) && (exponent >= -6)) {
  2202. if (exponent >= 0) {
  2203. result.Insert(end - scaleJ, '.');
  2204. } else {
  2205. result.Insert(begin - 1, "0."); //$NON-NLS-1$
  2206. result.Insert(begin + 1, CH_ZEROS, 0, -(int)exponent - 1);
  2207. }
  2208. } else {
  2209. int delta = end - begin;
  2210. int rem = (int)(exponent % 3);
  2211. if (rem != 0) {
  2212. // adjust exponent so it is a multiple of three
  2213. if (getUnscaledValue().signum() == 0) {
  2214. // zero value
  2215. rem = (rem < 0) ? -rem : 3 - rem;
  2216. exponent += rem;
  2217. } else {
  2218. // nonzero value
  2219. rem = (rem < 0) ? rem + 3 : rem;
  2220. exponent -= rem;
  2221. begin += rem;
  2222. }
  2223. if (delta < 3) {
  2224. for (int i = rem - delta; i > 0; i--) {
  2225. result.Insert(end++, '0');
  2226. }
  2227. }
  2228. }
  2229. if (end - begin >= 1) {
  2230. result.Insert(begin, '.');
  2231. end++;
  2232. }
  2233. if (exponent != 0) {
  2234. result.Insert(end, 'E');
  2235. if (exponent > 0) {
  2236. result.Insert(++end, '+');
  2237. }
  2238. result.Insert(++end, java.lang.Long.toString(exponent));
  2239. }
  2240. }
  2241. return result.toString();
  2242. }
  2243. /**
  2244. * Returns a string representation of this {@code BigDecimal}. No scientific
  2245. * notation is used. This methods adds zeros where necessary.
  2246. * <p>
  2247. * If this string representation is used to create a new instance, this
  2248. * instance is generally not identical to {@code this} as the precision
  2249. * changes.
  2250. * <p>
  2251. * {@code x.equals(new BigDecimal(x.toPlainString())} usually returns
  2252. * {@code false}.
  2253. * <p>
  2254. * {@code x.compareTo(new BigDecimal(x.toPlainString())} returns {@code 0}.
  2255. *
  2256. * @return a string representation of {@code this} without exponent part.
  2257. */
  2258. public String toPlainString() {
  2259. String intStr = getUnscaledValue().toString();
  2260. if ((scaleJ == 0) || ((isZero()) && (scaleJ < 0))) {
  2261. return intStr;
  2262. }
  2263. int begin = (signum() < 0) ? 1 : 0;
  2264. int delta = scaleJ;
  2265. // We take space for all digits, plus a possible decimal point, plus 'scale'
  2266. StringBuilder result = new StringBuilder(intStr.length() + 1 + java.lang.Math.abs(scaleJ));
  2267. if (begin == 1) {
  2268. // If the number is negative, we insert a '-' character at front
  2269. result.Append('-');
  2270. }
  2271. if (scaleJ > 0) {
  2272. delta -= (intStr.length() - begin);
  2273. if (delta >= 0) {
  2274. result.Append("0."); //$NON-NLS-1$
  2275. // To append zeros after the decimal point
  2276. for (; delta > CH_ZEROS.Length; delta -= CH_ZEROS.Length) {
  2277. result.Append(CH_ZEROS);
  2278. }
  2279. result.Append(CH_ZEROS, 0, delta);
  2280. result.Append(intStr.substring(begin));
  2281. } else {
  2282. delta = begin - delta;
  2283. result.Append(intStr.substring(begin, delta));
  2284. result.Append('.');
  2285. result.Append(intStr.substring(delta));
  2286. }
  2287. } else {// (scale <= 0)
  2288. result.Append(intStr.substring(begin));
  2289. // To append trailing zeros
  2290. for (; delta < -CH_ZEROS.Length; delta += CH_ZEROS.Length) {
  2291. result.Append(CH_ZEROS);
  2292. }
  2293. result.Append(CH_ZEROS, 0, -delta);
  2294. }
  2295. return result.toString();
  2296. }
  2297. /**
  2298. * Returns this {@code BigDecimal} as a big integer instance. A fractional
  2299. * part is discarded.
  2300. *
  2301. * @return this {@code BigDecimal} as a big integer instance.
  2302. */
  2303. public BigInteger toBigInteger() {
  2304. if ((scaleJ == 0) || (isZero())) {
  2305. return getUnscaledValue();
  2306. } else if (scaleJ < 0) {
  2307. return getUnscaledValue().multiply(Multiplication.powerOf10(-(long)scaleJ));
  2308. } else {// (scale > 0)
  2309. return getUnscaledValue().divide(Multiplication.powerOf10(scaleJ));
  2310. }
  2311. }
  2312. /**
  2313. * Returns this {@code BigDecimal} as a big integer instance if it has no
  2314. * fractional part. If this {@code BigDecimal} has a fractional part, i.e.
  2315. * if rounding would be necessary, an {@code ArithmeticException} is thrown.
  2316. *
  2317. * @return this {@code BigDecimal} as a big integer value.
  2318. * @throws ArithmeticException
  2319. * if rounding is necessary.
  2320. */
  2321. public BigInteger toBigIntegerExact() {
  2322. if ((scaleJ == 0) || (isZero())) {
  2323. return getUnscaledValue();
  2324. } else if (scaleJ < 0) {
  2325. return getUnscaledValue().multiply(Multiplication.powerOf10(-(long)scaleJ));
  2326. } else {// (scale > 0)
  2327. BigInteger[] integerAndFraction;
  2328. // An optimization before do a heavy division
  2329. if ((scaleJ > aproxPrecision()) || (scaleJ > getUnscaledValue().getLowestSetBit())) {
  2330. // math.08=Rounding necessary
  2331. throw new ArithmeticException("Rounding necessary"); //$NON-NLS-1$
  2332. }
  2333. integerAndFraction = getUnscaledValue().divideAndRemainder(Multiplication.powerOf10(scaleJ));
  2334. if (integerAndFraction[1].signum() != 0) {
  2335. // It exists a non-zero fractional part
  2336. // math.08=Rounding necessary
  2337. throw new ArithmeticException("Rounding necessary"); //$NON-NLS-1$
  2338. }
  2339. return integerAndFraction[0];
  2340. }
  2341. }
  2342. /**
  2343. * Returns this {@code BigDecimal} as an long value. Any fractional part is
  2344. * discarded. If the integral part of {@code this} is too big to be
  2345. * represented as an long, then {@code this} % 2^64 is returned.
  2346. *
  2347. * @return this {@code BigDecimal} as a long value.
  2348. */
  2349. public override long longValue() {
  2350. /* If scale <= -64 there are at least 64 trailing bits zero in 10^(-scale).
  2351. * If the scale is positive and very large the long value could be zero. */
  2352. return ((scaleJ <= -64) || (scaleJ > aproxPrecision())
  2353. ? 0L
  2354. : toBigInteger().longValue());
  2355. }
  2356. /**
  2357. * Returns this {@code BigDecimal} as a long value if it has no fractional
  2358. * part and if its value fits to the int range ([-2^{63}..2^{63}-1]). If
  2359. * these conditions are not met, an {@code ArithmeticException} is thrown.
  2360. *
  2361. * @return this {@code BigDecimal} as a long value.
  2362. * @throws ArithmeticException
  2363. * if rounding is necessary or the number doesn't fit in a long.
  2364. */
  2365. public long longValueExact() {
  2366. return valueExact(64);
  2367. }
  2368. /**
  2369. * Returns this {@code BigDecimal} as an int value. Any fractional part is
  2370. * discarded. If the integral part of {@code this} is too big to be
  2371. * represented as an int, then {@code this} % 2^32 is returned.
  2372. *
  2373. * @return this {@code BigDecimal} as a int value.
  2374. */
  2375. public override int intValue() {
  2376. /* If scale <= -32 there are at least 32 trailing bits zero in 10^(-scale).
  2377. * If the scale is positive and very large the long value could be zero. */
  2378. return ((scaleJ <= -32) || (scaleJ > aproxPrecision())
  2379. ? 0
  2380. : toBigInteger().intValue());
  2381. }
  2382. /**
  2383. * Returns this {@code BigDecimal} as a int value if it has no fractional
  2384. * part and if its value fits to the int range ([-2^{31}..2^{31}-1]). If
  2385. * these conditions are not met, an {@code ArithmeticException} is thrown.
  2386. *
  2387. * @return this {@code BigDecimal} as a int value.
  2388. * @throws ArithmeticException
  2389. * if rounding is necessary or the number doesn't fit in a int.
  2390. */
  2391. public int intValueExact() {
  2392. return (int)valueExact(32);
  2393. }
  2394. /**
  2395. * Returns this {@code BigDecimal} as a short value if it has no fractional
  2396. * part and if its value fits to the short range ([-2^{15}..2^{15}-1]). If
  2397. * these conditions are not met, an {@code ArithmeticException} is thrown.
  2398. *
  2399. * @return this {@code BigDecimal} as a short value.
  2400. * @throws ArithmeticException
  2401. * if rounding is necessary of the number doesn't fit in a
  2402. * short.
  2403. */
  2404. public short shortValueExact() {
  2405. return (short)valueExact(16);
  2406. }
  2407. /**
  2408. * Returns this {@code BigDecimal} as a byte value if it has no fractional
  2409. * part and if its value fits to the byte range ([-128..127]). If these
  2410. * conditions are not met, an {@code ArithmeticException} is thrown.
  2411. *
  2412. * @return this {@code BigDecimal} as a byte value.
  2413. * @throws ArithmeticException
  2414. * if rounding is necessary or the number doesn't fit in a byte.
  2415. */
  2416. public byte byteValueExact() {
  2417. return (byte)valueExact(8);
  2418. }
  2419. /**
  2420. * Returns this {@code BigDecimal} as a float value. If {@code this} is too
  2421. * big to be represented as an float, then {@code Float.POSITIVE_INFINITY}
  2422. * or {@code Float.NEGATIVE_INFINITY} is returned.
  2423. * <p>
  2424. * Note, that if the unscaled value has more than 24 significant digits,
  2425. * then this decimal cannot be represented exactly in a float variable. In
  2426. * this case the result is rounded.
  2427. * <p>
  2428. * For example, if the instance {@code x1 = new BigDecimal("0.1")} cannot be
  2429. * represented exactly as a float, and thus {@code x1.equals(new
  2430. * BigDecimal(x1.folatValue())} returns {@code false} for this case.
  2431. * <p>
  2432. * Similarly, if the instance {@code new BigDecimal(16777217)} is converted
  2433. * to a float, the result is {@code 1.6777216E}7.
  2434. *
  2435. * @return this {@code BigDecimal} as a float value.
  2436. */
  2437. public override float floatValue() {
  2438. /* A similar code like in doubleValue() could be repeated here,
  2439. * but this simple implementation is quite efficient. */
  2440. float floatResult = signum();
  2441. long powerOfTwo = this.bitLengthJ - (long)(scaleJ / LOG10_2);
  2442. if ((powerOfTwo < -149) || (floatResult == 0.0f)) {
  2443. // Cases which 'this' is very small
  2444. floatResult *= 0.0f;
  2445. } else if (powerOfTwo > 129) {
  2446. // Cases which 'this' is very large
  2447. floatResult *= java.lang.Float.POSITIVE_INFINITY;
  2448. } else {
  2449. floatResult = (float)doubleValue();
  2450. }
  2451. return floatResult;
  2452. }
  2453. /**
  2454. * Returns this {@code BigDecimal} as a double value. If {@code this} is too
  2455. * big to be represented as an float, then {@code Double.POSITIVE_INFINITY}
  2456. * or {@code Double.NEGATIVE_INFINITY} is returned.
  2457. * <p>
  2458. * Note, that if the unscaled value has more than 53 significant digits,
  2459. * then this decimal cannot be represented exactly in a double variable. In
  2460. * this case the result is rounded.
  2461. * <p>
  2462. * For example, if the instance {@code x1 = new BigDecimal("0.1")} cannot be
  2463. * represented exactly as a double, and thus {@code x1.equals(new
  2464. * BigDecimal(x1.doubleValue())} returns {@code false} for this case.
  2465. * <p>
  2466. * Similarly, if the instance {@code new BigDecimal(9007199254740993L)} is
  2467. * converted to a double, the result is {@code 9.007199254740992E15}.
  2468. * <p>
  2469. *
  2470. * @return this {@code BigDecimal} as a double value.
  2471. */
  2472. public override double doubleValue() {
  2473. int sign = signum();
  2474. int exponent = 1076; // bias + 53
  2475. int lowestSetBit;
  2476. int discardedSize;
  2477. long powerOfTwo = this.bitLengthJ - (long)(scaleJ / LOG10_2);
  2478. long bits; // IEEE-754 Standard
  2479. long tempBits; // for temporal calculations
  2480. BigInteger mantisa;
  2481. if ((powerOfTwo < -1074) || (sign == 0)) {
  2482. // Cases which 'this' is very small
  2483. return (sign * 0.0d);
  2484. } else if (powerOfTwo > 1025) {
  2485. // Cases which 'this' is very large
  2486. return (sign * java.lang.Double.POSITIVE_INFINITY);
  2487. }
  2488. mantisa = getUnscaledValue().abs();
  2489. // Let be: this = [u,s], with s > 0
  2490. if (scaleJ <= 0) {
  2491. // mantisa = abs(u) * 10^s
  2492. mantisa = mantisa.multiply(Multiplication.powerOf10(-scaleJ));
  2493. } else {// (scale > 0)
  2494. BigInteger[] quotAndRem;
  2495. BigInteger powerOfTen = Multiplication.powerOf10(scaleJ);
  2496. int k = 100 - (int)powerOfTwo;
  2497. int compRem;
  2498. if (k > 0) {
  2499. /* Computing (mantisa * 2^k) , where 'k' is a enough big
  2500. * power of '2' to can divide by 10^s */
  2501. mantisa = mantisa.shiftLeft(k);
  2502. exponent -= k;
  2503. }
  2504. // Computing (mantisa * 2^k) / 10^s
  2505. quotAndRem = mantisa.divideAndRemainder(powerOfTen);
  2506. // To check if the fractional part >= 0.5
  2507. compRem = quotAndRem[1].shiftLeftOneBit().compareTo(powerOfTen);
  2508. // To add two rounded bits at end of mantisa
  2509. mantisa = quotAndRem[0].shiftLeft(2).add(
  2510. BigInteger.valueOf((compRem * (compRem + 3)) / 2 + 1));
  2511. exponent -= 2;
  2512. }
  2513. lowestSetBit = mantisa.getLowestSetBit();
  2514. discardedSize = mantisa.bitLength() - 54;
  2515. if (discardedSize > 0) {// (n > 54)
  2516. // mantisa = (abs(u) * 10^s) >> (n - 54)
  2517. bits = mantisa.shiftRight(discardedSize).longValue();
  2518. tempBits = bits;
  2519. // #bits = 54, to check if the discarded fraction produces a carry
  2520. if ((((bits & 1) == 1) && (lowestSetBit < discardedSize))
  2521. || ((bits & 3) == 3)) {
  2522. bits += 2;
  2523. }
  2524. } else {// (n <= 54)
  2525. // mantisa = (abs(u) * 10^s) << (54 - n)
  2526. bits = mantisa.longValue() << -discardedSize;
  2527. tempBits = bits;
  2528. // #bits = 54, to check if the discarded fraction produces a carry:
  2529. if ((bits & 3) == 3) {
  2530. bits += 2;
  2531. }
  2532. }
  2533. // Testing bit 54 to check if the carry creates a new binary digit
  2534. if ((bits & 0x40000000000000L) == 0) {
  2535. // To drop the last bit of mantisa (first discarded)
  2536. bits >>= 1;
  2537. // exponent = 2^(s-n+53+bias)
  2538. exponent += discardedSize;
  2539. } else {// #bits = 54
  2540. bits >>= 2;
  2541. exponent += discardedSize + 1;
  2542. }
  2543. // To test if the 53-bits number fits in 'double'
  2544. if (exponent > 2046) {// (exponent - bias > 1023)
  2545. return (sign * java.lang.Double.POSITIVE_INFINITY);
  2546. } else if (exponent <= 0) {// (exponent - bias <= -1023)
  2547. // Denormalized numbers (having exponent == 0)
  2548. if (exponent < -53) {// exponent - bias < -1076
  2549. return (sign * 0.0d);
  2550. }
  2551. // -1076 <= exponent - bias <= -1023
  2552. // To discard '- exponent + 1' bits
  2553. bits = tempBits >> 1;
  2554. tempBits = bits & (java.dotnet.lang.Operator.shiftRightUnsignet( -1L , (63 + exponent)));
  2555. bits >>= (-exponent );
  2556. // To test if after discard bits, a new carry is generated
  2557. if (((bits & 3) == 3) || (((bits & 1) == 1) && (tempBits != 0)
  2558. && (lowestSetBit < discardedSize))) {
  2559. bits += 1;
  2560. }
  2561. exponent = 0;
  2562. bits >>= 1;
  2563. }
  2564. // Construct the 64 double bits: [sign(1), exponent(11), mantisa(52)]
  2565. bits = (sign == -1 ? java.lang.Long.MIN_VALUE : 0)//(sign & 0x8000000000000000L) // bei -1 Long.MIN_VALUE sonst 0
  2566. | ((long)exponent << 52)
  2567. | (bits & 0xFFFFFFFFFFFFFL);
  2568. return java.lang.Double.longBitsToDouble(bits);
  2569. }
  2570. /**
  2571. * Returns the unit in the last place (ULP) of this {@code BigDecimal}
  2572. * instance. An ULP is the distance to the nearest big decimal with the same
  2573. * precision.
  2574. * <p>
  2575. * The amount of a rounding error in the evaluation of a floating-point
  2576. * operation is often expressed in ULPs. An error of 1 ULP is often seen as
  2577. * a tolerable error.
  2578. * <p>
  2579. * For class {@code BigDecimal}, the ULP of a number is simply 10^(-scale).
  2580. * <p>
  2581. * For example, {@code new BigDecimal(0.1).ulp()} returns {@code 1E-55}.
  2582. *
  2583. * @return unit in the last place (ULP) of this {@code BigDecimal} instance.
  2584. */
  2585. public BigDecimal ulp() {
  2586. return valueOf(1, scaleJ);
  2587. }
  2588. /* Private Methods */
  2589. /**
  2590. * It does all rounding work of the public method
  2591. * {@code round(MathContext)}, performing an inplace rounding
  2592. * without creating a new object.
  2593. *
  2594. * @param mc
  2595. * the {@code MathContext} for perform the rounding.
  2596. * @see #round(MathContext)
  2597. */
  2598. private void inplaceRound(MathContext mc) {
  2599. int mcPrecision = mc.getPrecision();
  2600. if (aproxPrecision() - mcPrecision <= 0 || mcPrecision == 0) {
  2601. return;
  2602. }
  2603. int discardedPrecision = precision() - mcPrecision;
  2604. // If no rounding is necessary it returns immediately
  2605. if ((discardedPrecision <= 0)) {
  2606. return;
  2607. }
  2608. // When the number is small perform an efficient rounding
  2609. if (this.bitLengthJ < 64) {
  2610. smallRound(mc, discardedPrecision);
  2611. return;
  2612. }
  2613. // Getting the integer part and the discarded fraction
  2614. BigInteger sizeOfFraction = Multiplication.powerOf10(discardedPrecision);
  2615. BigInteger[] integerAndFraction = getUnscaledValue().divideAndRemainder(sizeOfFraction);
  2616. long newScale = (long)scaleJ - discardedPrecision;
  2617. int compRem;
  2618. BigDecimal tempBD;
  2619. // If the discarded fraction is non-zero, perform rounding
  2620. if (integerAndFraction[1].signum() != 0) {
  2621. // To check if the discarded fraction >= 0.5
  2622. compRem = (integerAndFraction[1].abs().shiftLeftOneBit().compareTo(sizeOfFraction));
  2623. // To look if there is a carry
  2624. compRem = roundingBehavior( integerAndFraction[0].testBit(0) ? 1 : 0,
  2625. integerAndFraction[1].signum() * (5 + compRem),
  2626. mc.getRoundingMode());
  2627. if (compRem != 0) {
  2628. integerAndFraction[0] = integerAndFraction[0].add(BigInteger.valueOf(compRem));
  2629. }
  2630. tempBD = new BigDecimal(integerAndFraction[0]);
  2631. // If after to add the increment the precision changed, we normalize the size
  2632. if (tempBD.precision() > mcPrecision) {
  2633. integerAndFraction[0] = integerAndFraction[0].divide(BigInteger.TEN);
  2634. newScale--;
  2635. }
  2636. }
  2637. // To update all internal fields
  2638. scaleJ = toIntScale(newScale);
  2639. precisionJ = mcPrecision;
  2640. setUnscaledValue(integerAndFraction[0]);
  2641. }
  2642. private static int longCompareTo(long value1, long value2) {
  2643. return value1 > value2 ? 1 : (value1 < value2 ? -1 : 0);
  2644. }
  2645. /**
  2646. * This method implements an efficient rounding for numbers which unscaled
  2647. * value fits in the type {@code long}.
  2648. *
  2649. * @param mc
  2650. * the context to use
  2651. * @param discardedPrecision
  2652. * the number of decimal digits that are discarded
  2653. * @see #round(MathContext)
  2654. */
  2655. private void smallRound(MathContext mc, int discardedPrecision) {
  2656. long sizeOfFraction = LONG_TEN_POW[discardedPrecision];
  2657. long newScale = (long)scaleJ - discardedPrecision;
  2658. long unscaledVal = smallValue;
  2659. // Getting the integer part and the discarded fraction
  2660. long integer = unscaledVal / sizeOfFraction;
  2661. long fraction = unscaledVal % sizeOfFraction;
  2662. int compRem;
  2663. // If the discarded fraction is non-zero perform rounding
  2664. if (fraction != 0) {
  2665. // To check if the discarded fraction >= 0.5
  2666. compRem = longCompareTo(java.lang.Math.abs(fraction) << 1,sizeOfFraction);
  2667. // To look if there is a carry
  2668. integer += roundingBehavior( ((int)integer) & 1,
  2669. java.lang.Long.signum(fraction) * (5 + compRem),
  2670. mc.getRoundingMode());
  2671. // If after to add the increment the precision changed, we normalize the size
  2672. if (java.lang.Math.log10(java.lang.Math.abs(integer)) >= mc.getPrecision()) {
  2673. integer /= 10;
  2674. newScale--;
  2675. }
  2676. }
  2677. // To update all internal fields
  2678. scaleJ = toIntScale(newScale);
  2679. precisionJ = mc.getPrecision();
  2680. smallValue = integer;
  2681. bitLengthJ = bitLength(integer);
  2682. intVal = null;
  2683. }
  2684. /**
  2685. * Return an increment that can be -1,0 or 1, depending of
  2686. * {@code roundingMode}.
  2687. *
  2688. * @param parityBit
  2689. * can be 0 or 1, it's only used in the case
  2690. * {@code HALF_EVEN}
  2691. * @param fraction
  2692. * the mantisa to be analyzed
  2693. * @param roundingMode
  2694. * the type of rounding
  2695. * @return the carry propagated after rounding
  2696. */
  2697. private static int roundingBehavior(int parityBit, int fraction, RoundingMode roundingMode) {
  2698. int increment = 0; // the carry after rounding
  2699. if (roundingMode.ordinal()==RoundingMode.UNNECESSARY.ordinal()) {
  2700. if (fraction != 0) {
  2701. // math.08=Rounding necessary
  2702. throw new ArithmeticException("Rounding necessary"); //$NON-NLS-1$
  2703. }
  2704. }
  2705. else if (roundingMode.ordinal()==RoundingMode.UP.ordinal()) {
  2706. increment = java.lang.Integer.signum(fraction);
  2707. }
  2708. else if (roundingMode.ordinal()==RoundingMode.DOWN.ordinal()) {
  2709. }
  2710. else if (roundingMode.ordinal()==RoundingMode.CEILING.ordinal()) {
  2711. increment = java.lang.Math.max(java.lang.Integer.signum(fraction), 0);
  2712. }
  2713. else if (roundingMode.ordinal()==RoundingMode.FLOOR.ordinal()) {
  2714. increment = java.lang.Math.min(java.lang.Integer.signum(fraction), 0);
  2715. }
  2716. else if (roundingMode.ordinal()==RoundingMode.HALF_UP.ordinal()) {
  2717. if (java.lang.Math.abs(fraction) >= 5) {
  2718. increment = java.lang.Integer.signum(fraction);
  2719. }
  2720. }
  2721. else if (roundingMode.ordinal()==RoundingMode.HALF_DOWN.ordinal()) {
  2722. if (java.lang.Math.abs(fraction) > 5) {
  2723. increment = java.lang.Integer.signum(fraction);
  2724. }
  2725. }
  2726. else if (roundingMode.ordinal()==RoundingMode.HALF_EVEN.ordinal()) {
  2727. if (java.lang.Math.abs(fraction) + parityBit > 5) {
  2728. increment = java.lang.Integer.signum(fraction);
  2729. }
  2730. }
  2731. return increment;
  2732. }
  2733. /**
  2734. * If {@code intVal} has a fractional part throws an exception,
  2735. * otherwise it counts the number of bits of value and checks if it's out of
  2736. * the range of the primitive type. If the number fits in the primitive type
  2737. * returns this number as {@code long}, otherwise throws an
  2738. * exception.
  2739. *
  2740. * @param bitLengthJOfType
  2741. * number of bits of the type whose value will be calculated
  2742. * exactly
  2743. * @return the exact value of the integer part of {@code BigDecimal}
  2744. * when is possible
  2745. * @throws ArithmeticException when rounding is necessary or the
  2746. * number don't fit in the primitive type
  2747. */
  2748. private long valueExact(int bitLengthJOfType) {
  2749. BigInteger bigInteger = toBigIntegerExact();
  2750. if (bigInteger.bitLength() < bitLengthJOfType) {
  2751. // It fits in the primitive type
  2752. return bigInteger.longValue();
  2753. }
  2754. // math.08=Rounding necessary
  2755. throw new ArithmeticException("Rounding necessary"); //$NON-NLS-1$
  2756. }
  2757. /**
  2758. * If the precision already was calculated it returns that value, otherwise
  2759. * it calculates a very good approximation efficiently . Note that this
  2760. * value will be {@code precision()} or {@code precision()-1}
  2761. * in the worst case.
  2762. *
  2763. * @return an approximation of {@code precision()} value
  2764. */
  2765. private int aproxPrecision() {
  2766. return ((precisionJ > 0)
  2767. ? precisionJ
  2768. : (int)((this.bitLengthJ - 1) * LOG10_2)) + 1;
  2769. }
  2770. /**
  2771. * It tests if a scale of type {@code long} fits in 32 bits. It
  2772. * returns the same scale being casted to {@code int} type when is
  2773. * possible, otherwise throws an exception.
  2774. *
  2775. * @param longScale
  2776. * a 64 bit scale
  2777. * @return a 32 bit scale when is possible
  2778. * @throws ArithmeticException when {@code scale} doesn't
  2779. * fit in {@code int} type
  2780. * @see #scale
  2781. */
  2782. private static int toIntScale(long longScale) {
  2783. if (longScale < java.lang.Integer.MIN_VALUE) {
  2784. // math.09=Overflow
  2785. throw new java.lang.ArithmeticException("Overflow"); //$NON-NLS-1$
  2786. } else if (longScale > java.lang.Integer.MAX_VALUE) {
  2787. // math.0A=Underflow
  2788. throw new java.lang.ArithmeticException("Underflow"); //$NON-NLS-1$
  2789. } else {
  2790. return (int)longScale;
  2791. }
  2792. }
  2793. /**
  2794. * It returns the value 0 with the most approximated scale of type
  2795. * {@code int}. if {@code longScale > Integer.MAX_VALUE} the
  2796. * scale will be {@code Integer.MAX_VALUE}; if
  2797. * {@code longScale < Integer.MIN_VALUE} the scale will be
  2798. * {@code Integer.MIN_VALUE}; otherwise {@code longScale} is
  2799. * casted to the type {@code int}.
  2800. *
  2801. * @param longScale
  2802. * the scale to which the value 0 will be scaled.
  2803. * @return the value 0 scaled by the closer scale of type {@code int}.
  2804. * @see #scale
  2805. */
  2806. private static BigDecimal zeroScaledBy(long longScale) {
  2807. if (longScale == (int) longScale) {
  2808. return valueOf(0,(int)longScale);
  2809. }
  2810. if (longScale >= 0) {
  2811. return new BigDecimal( 0, java.lang.Integer.MAX_VALUE);
  2812. }
  2813. return new BigDecimal( 0, java.lang.Integer.MIN_VALUE);
  2814. }
  2815. /**
  2816. * Assignes all transient fields upon deserialization of a
  2817. * {@code BigDecimal} instance (bitLengthJ and smallValue). The transient
  2818. * field precision is assigned lazily.
  2819. *
  2820. private void readObject(ObjectInputStream in) throws IOException,
  2821. ClassNotFoundException {
  2822. in.defaultReadObject();
  2823. this.bitLengthJ = intVal.bitLengthJ();
  2824. if (this.bitLengthJ < 64) {
  2825. this.smallValue = intVal.longValue();
  2826. }
  2827. }
  2828. /**
  2829. * Prepares this {@code BigDecimal} for serialization, i.e. the
  2830. * non-transient field {@code intVal} is assigned.
  2831. *
  2832. private void writeObject(ObjectOutputStream out) throws IOException {
  2833. getUnscaledValue();
  2834. out.defaultWriteObject();
  2835. }*/
  2836. private BigInteger getUnscaledValue() {
  2837. if(intVal == null) {
  2838. intVal = BigInteger.valueOf(smallValue);
  2839. }
  2840. return intVal;
  2841. }
  2842. private void setUnscaledValue(BigInteger unscaledValue) {
  2843. this.intVal = unscaledValue;
  2844. this.bitLengthJ = unscaledValue.bitLength();
  2845. if(this.bitLengthJ < 64) {
  2846. this.smallValue = unscaledValue.longValue();
  2847. }
  2848. }
  2849. private static int bitLength(long smallValue) {
  2850. if(smallValue < 0) {
  2851. smallValue = ~smallValue;
  2852. }
  2853. return 64 - java.lang.Long.numberOfLeadingZeros(smallValue);
  2854. }
  2855. private static int bitLength(int smallValue) {
  2856. if(smallValue < 0) {
  2857. smallValue = ~smallValue;
  2858. }
  2859. return 32 - java.lang.Integer.numberOfLeadingZeros(smallValue);
  2860. }
  2861. public override short shortValue()
  2862. {
  2863. return (short)this.intValue();
  2864. }
  2865. public override byte byteValue()
  2866. {
  2867. return (byte)this.intValue();
  2868. }
  2869. }
  2870. }