summaryrefslogtreecommitdiff
path: root/src/library/scala/BigDecimal.scala
blob: b4d4732951dc12b042bcc342c0dc9e4ccca6c62a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
/*                     __                                               *\
**     ________ ___   / /  ___     Scala API                            **
**    / __/ __// _ | / /  / _ |    (c) 2007-2009, LAMP/EPFL             **
**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
** /____/\___/_/ |_/____/_/ | |                                         **
**                          |/                                          **
\*                                                                      */

// $Id$

package scala

import java.math.{BigDecimal => BigDec}
import java.math.MathContext

/**
 *  @author  Stephane Micheloud
 *  @version 1.0
 */
object BigDecimal
{
  @serializable
  object RoundingMode extends Enumeration(java.math.RoundingMode.values map (_.toString) : _*) {
    type RoundingMode = Value
    val UP, DOWN, CEILING, FLOOR, HALF_UP, HALF_DOWN, HALF_EVEN, UNNECESSARY = Value
  }

  private val minCached = -512
  private val maxCached = 512
  private lazy val cache = new Array[BigDecimal](maxCached - minCached + 1)

  val defaultMathContext = MathContext.UNLIMITED

  /** Constructs a <code>BigDecimal</code> whose value is equal to that of the
   *  specified <code>Integer</code> value.
   *
   *  @param i the specified integer value
   *  @return  the constructed <code>BigDecimal</code>
   */
  def apply(i: Int): BigDecimal = apply(i, defaultMathContext)
  def apply(i: Int, mc: MathContext): BigDecimal =
    if (minCached <= i && i <= maxCached) {
      val offset = i - minCached
      var n = cache(offset)
      if (n eq null) { n = new BigDecimal(BigDec.valueOf(i), mc); cache(offset) = n }
      n
    } else new BigDecimal(BigDec.valueOf(i), mc)

  /** Constructs a <code>BigDecimal</code> whose value is equal to that of the
   *  specified long value.
   *
   *  @param l the specified long value
   *  @return  the constructed <code>BigDecimal</code>
   */
  def apply(l: Long): BigDecimal =
    if (minCached <= l && l <= maxCached) apply(l.toInt)
    else new BigDecimal(BigDec.valueOf(l), defaultMathContext)

  def apply(l: Long, mc: MathContext): BigDecimal =
    new BigDecimal(new BigDec(l, mc), mc)

  /** Constructs a <code>BigDecimal</code> whose unscaled value is equal to that
   *  of the specified long value.
   *
   *  @param  unscaledVal the value
   *  @param  scale       the scale
   *  @return the constructed <code>BigDecimal</code>
   */
  def apply(unscaledVal: Long, scale: Int): BigDecimal =
    apply(BigInt(unscaledVal), scale)

  def apply(unscaledVal: Long, scale: Int, mc: MathContext): BigDecimal =
    apply(BigInt(unscaledVal), scale, mc)

  /** Constructs a <code>BigDecimal</code> whose value is equal to that of the
   *  specified double value.
   *
   *  @param d the specified <code>Double</code> value
   *  @return  the constructed <code>BigDecimal</code>
   */
  def apply(d: Double): BigDecimal = apply(d, defaultMathContext)
  // note we don't use the static valueOf because it doesn't let us supply
  // a MathContext, but we should be duplicating its logic, modulo caching.
  def apply(d: Double, mc: MathContext): BigDecimal =
    new BigDecimal(new BigDec(java.lang.Double.toString(d), mc), mc)

  /** Translates a character array representation of a <code>BigDecimal</code>
   *  into a <code>BigDecimal</code>.
   */
  def apply(x: Array[Char]): BigDecimal = apply(x, defaultMathContext)
  def apply(x: Array[Char], mc: MathContext): BigDecimal =
    new BigDecimal(new BigDec(x.toString, mc), mc)

  /** Translates the decimal String representation of a <code>BigDecimal</code>
   *  into a <code>BigDecimal</code>.
   */
  def apply(x: String): BigDecimal = apply(x, defaultMathContext)
  def apply(x: String, mc: MathContext): BigDecimal =
    new BigDecimal(new BigDec(x, mc), mc)

  /** Constructs a <code>BigDecimal</code> whose value is equal to that of the
   *  specified <code>BigInt</code> value.
   *
   *  @param x the specified <code>BigInt</code> value
   *  @return  the constructed <code>BigDecimal</code>
   */
  def apply(x: BigInt): BigDecimal = apply(x, defaultMathContext)
  def apply(x: BigInt, mc: MathContext): BigDecimal =
    new BigDecimal(new BigDec(x.bigInteger, mc), mc)

  /** Constructs a <code>BigDecimal</code> whose unscaled value is equal to that
   *  of the specified <code>BigInt</code> value.
   *
   *  @param unscaledVal the specified <code>BigInt</code> value
   *  @param scale       the scale
   *  @return  the constructed <code>BigDecimal</code>
   */
  def apply(unscaledVal: BigInt, scale: Int): BigDecimal = apply(unscaledVal, scale, defaultMathContext)
  def apply(unscaledVal: BigInt, scale: Int, mc: MathContext): BigDecimal =
    new BigDecimal(new BigDec(unscaledVal.bigInteger, scale, mc), mc)

  def apply(bd: BigDec): BigDecimal = apply(bd, defaultMathContext)
  def apply(bd: BigDec, mc: MathContext): BigDecimal = new BigDecimal(bd, mc)

  /** Implicit conversion from <code>Int</code> to <code>BigDecimal</code>. */
  implicit def int2bigDecimal(i: Int): BigDecimal = apply(i)

  /** Implicit conversion from <code>Long</code> to <code>BigDecimal</code>. */
  implicit def long2bigDecimal(l: Long): BigDecimal = apply(l)

  /** Implicit conversion from <code>Float</code> to <code>BigDecimal</code>.
   *  @since 2.8
   */
  implicit def float2bigDecimal(f: Float): BigDecimal = apply(f)

  /** Implicit conversion from <code>Double</code> to <code>BigDecimal</code>. */
  implicit def double2bigDecimal(d: Double): BigDecimal = apply(d)

  /** Implicit conversion from <code>String</code> to <code>BigDecimal</code>.
   *  @since 2.8
   */
  implicit def string2bigDecimal(s: String): BigDecimal = apply(s)

  /** Implicit conversion from <code>BigInt</code> to <code>BigDecimal</code>.
   *  @since 2.8
   */
  implicit def bigInt2bigDecimal(x: BigInt): BigDecimal = apply(x)
}

/**
 *  @author  Stephane Micheloud
 *  @version 1.0
 */
@serializable
class BigDecimal(
  val bigDecimal: BigDec,
  val mc: MathContext)
extends java.lang.Number
{
  def this(bigDecimal: BigDec) = this(bigDecimal, BigDecimal.defaultMathContext)
  import BigDecimal.RoundingMode._

  /** Cuts way down on the wrapper noise. */
  private implicit def bigdec2BigDecimal(x: BigDec): BigDecimal = new BigDecimal(x, mc)

  /** Returns the hash code for this BigDecimal. */
  override def hashCode(): Int = this.bigDecimal.hashCode()

  /** Compares this BigDecimal with the specified value for equality.
   *  Will only claim equality with scala.BigDecimal and java.math.BigDecimal.
   */
  override def equals (that: Any): Boolean = that match {
    case that: BigDecimal           => this equals that
    case that: BigDec               => this equals BigDecimal(that)
    case _                          => false
  }

  /** Compares this BigDecimal with the specified BigDecimal for equality.
   */
  def equals (that: BigDecimal): Boolean = compare(that) == 0

  /** Compares this BigDecimal with the specified BigDecimal
   */
  def compare (that: BigDecimal): Int = this.bigDecimal compareTo that.bigDecimal

  /** Less-than-or-equals comparison of BigDecimals
   */
  def <= (that: BigDecimal): Boolean = compare(that) <= 0

  /** Greater-than-or-equals comparison of BigDecimals
   */
  def >= (that: BigDecimal): Boolean = compare(that) >= 0

  /** Less-than of BigDecimals
   */
  def <  (that: BigDecimal): Boolean = compare(that) <  0

  /** Greater-than comparison of BigDecimals
   */
  def >  (that: BigDecimal): Boolean = compare(that) > 0

  /** Addition of BigDecimals
   */
  def +  (that: BigDecimal): BigDecimal = this.bigDecimal.add(that.bigDecimal, mc)

  /** Subtraction of BigDecimals
   */
  def -  (that: BigDecimal): BigDecimal = this.bigDecimal.subtract(that.bigDecimal, mc)

  /** Multiplication of BigDecimals
   */
  def *  (that: BigDecimal): BigDecimal = this.bigDecimal.multiply(that.bigDecimal, mc)

  /** Division of BigDecimals
   */
  def /  (that: BigDecimal): BigDecimal = this.bigDecimal.divide(that.bigDecimal, mc)

  /** Division and Remainder - returns tuple containing the result of
   *  divideToIntegralValue and the remainder.
   */
  def /% (that: BigDecimal): (BigDecimal, BigDecimal) =
    this.bigDecimal.divideAndRemainder(that.bigDecimal, mc) match {
      case Array(q, r)  => (q, r)
    }

  /** Divide to Integral value.
   */
  def quot (that: BigDecimal): BigDecimal =
    this.bigDecimal.divideToIntegralValue(that.bigDecimal, mc)

  /** Returns the minimum of this and that
   */
  def min (that: BigDecimal): BigDecimal = this.bigDecimal min that.bigDecimal

  /** Returns the maximum of this and that
   */
  def max (that: BigDecimal): BigDecimal = this.bigDecimal max that.bigDecimal

  /** Remainder after dividing this by that.
   */
  def remainder (that: BigDecimal): BigDecimal = this.bigDecimal.remainder(that.bigDecimal, mc)

  /** Returns a BigDecimal whose value is this ** n.
   */
  def pow (n: Int): BigDecimal = this.bigDecimal.pow(n, mc)

  /** Returns a BigDecimal whose value is the negation of this BigDecimal
   */
  def unary_- : BigDecimal = this.bigDecimal.negate(mc)

  /** Returns the absolute value of this BigDecimal
   */
  def abs: BigDecimal = this.bigDecimal abs mc

  /** Returns the sign of this BigDecimal, i.e.
   *   -1 if it is less than 0,
   *   +1 if it is greater than 0
   *   0  if it is equal to 0
   */
  def signum: Int = this.bigDecimal.signum()

  /** Returns the precision of this <code>BigDecimal</code>.
   */
  def precision: Int = this.bigDecimal.precision()

  /** Returns a BigDecimal rounded according to the MathContext settings.
   */
  def round(mc: MathContext): BigDecimal = this.bigDecimal round mc

  /** Returns the scale of this <code>BigDecimal</code>.
   */
  def scale: Int = this.bigDecimal.scale()

  /** Returns the size of an ulp, a unit in the last place, of this BigDecimal.
   */
  def ulp: BigDecimal = this.bigDecimal.ulp

  /** Returns a new BigDecimal based on the supplied MathContext.
   */
  def apply(mc: MathContext): BigDecimal = BigDecimal(this.bigDecimal.toString, mc)

  /** Returns a <code>BigDecimal</code> whose scale is the specified value, and whose value is
   *  numerically equal to this BigDecimal's.
   */
  def setScale(scale: Int): BigDecimal = this.bigDecimal setScale scale

  def setScale(scale: Int, mode: RoundingMode): BigDecimal =
    this.bigDecimal.setScale(scale, mode.id)

  /** Converts this BigDecimal to a <tt>byte</tt>.
   *  If the BigDecimal is too big to fit in a byte, only the low-order 8 bits are returned.
   *  Note that this conversion can lose information about the overall magnitude of the
   *  BigDecimal value as well as return a result with the opposite sign.
   */
  override def byteValue   = intValue.toByte

  /** Converts this BigDecimal to a <tt>short</tt>.
   *  If the BigDecimal is too big to fit in a byte, only the low-order 16 bits are returned.
   *  Note that this conversion can lose information about the overall magnitude of the
   *  BigDecimal value as well as return a result with the opposite sign.
   */
  override def shortValue  = intValue.toShort

  /** Converts this BigDecimal to a <tt>char</tt>.
   *  If the BigDecimal is too big to fit in a char, only the low-order 16 bits are returned.
   *  Note that this conversion can lose information about the overall magnitude of the
   *  BigDecimal value and that it always returns a positive result.
   */
  def charValue   = intValue.toChar

  /** Converts this BigDecimal to an <tt>int</tt>.
   *  If the BigDecimal is too big to fit in a char, only the low-order 32 bits
   *  are returned. Note that this conversion can lose information about the
   *  overall magnitude of the BigDecimal value as well as return a result with
   *  the opposite sign.
   */
  def intValue    = this.bigDecimal.intValue

  /** Converts this BigDecimal to a <tt>Long</tt>.
   *  If the BigDecimal is too big to fit in a char, only the low-order 64 bits
   *  are returned. Note that this conversion can lose information about the
   *  overall magnitude of the BigDecimal value as well as return a result with
   *  the opposite sign.
   */
  def longValue   = this.bigDecimal.longValue

  /** Converts this BigDecimal to a <tt>float</tt>.
   *  if this BigDecimal has too great a magnitude to represent as a float,
   *  it will be converted to <code>Float.NEGATIVE_INFINITY</code> or
   *  <code>Float.POSITIVE_INFINITY</code> as appropriate.
   */
  def floatValue  = this.bigDecimal.floatValue

  /** Converts this BigDecimal to a <tt>Double</tt>.
   *  if this BigDecimal has too great a magnitude to represent as a float,
   *  it will be converted to <code>Float.NEGATIVE_INFINITY</code> or
   *  <code>Float.POSITIVE_INFINITY</code> as appropriate.
   */
  def doubleValue = this.bigDecimal.doubleValue

  /** This BigDecimal as an exact value.
   */
  def byteValueExact: Byte    = bigDecimal.byteValueExact
  def shortValueExact: Short  = bigDecimal.shortValueExact
  def intValueExact: Int      = bigDecimal.intValueExact
  def longValueExact: Long    = bigDecimal.longValueExact

  /** See <code>Iterator.range</code>. */
  def until(end: BigDecimal, step: BigDecimal) = Range.BigDecimal(this, end, step)

  /** like <code>until</code>, but includes the last index */
  def to(end: BigDecimal, step: BigDecimal) = Range.BigDecimal.inclusive(this, end, step)

  /** Converts this <code>BigDecimal</code> to a scala.BigInt.
   */
  def toBigInt(): BigInt = new BigInt(this.bigDecimal.toBigInteger())

  /** Converts this <code>BigDecimal</code> to a scala.BigInt if it
   *  can be done losslessly, returning Some(BigInt) or None.
   */
  def toBigIntExact(): Option[BigInt] =
    try Some(new BigInt(this.bigDecimal.toBigIntegerExact()))
    catch { case _: ArithmeticException => None }

  /** Returns the decimal String representation of this BigDecimal.
   */
  override def toString(): String = this.bigDecimal.toString()

}