Skip to content

Commit ecb785f

Browse files
juliuszsompolskihvanhovell
authored andcommitted
[SPARK-26038] Decimal toScalaBigInt/toJavaBigInteger for decimals not fitting in long
## What changes were proposed in this pull request? Fix Decimal `toScalaBigInt` and `toJavaBigInteger` used to only work for decimals not fitting long. ## How was this patch tested? Added test to DecimalSuite. Closes apache#23022 from juliuszsompolski/SPARK-26038. Authored-by: Juliusz Sompolski <[email protected]> Signed-off-by: Herman van Hovell <[email protected]>
1 parent 8e8d117 commit ecb785f

File tree

2 files changed

+25
-2
lines changed

2 files changed

+25
-2
lines changed

sql/catalyst/src/main/scala/org/apache/spark/sql/types/Decimal.scala

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -185,9 +185,21 @@ final class Decimal extends Ordered[Decimal] with Serializable {
185185
}
186186
}
187187

188-
def toScalaBigInt: BigInt = BigInt(toLong)
188+
def toScalaBigInt: BigInt = {
189+
if (decimalVal.ne(null)) {
190+
decimalVal.toBigInt()
191+
} else {
192+
BigInt(toLong)
193+
}
194+
}
189195

190-
def toJavaBigInteger: java.math.BigInteger = java.math.BigInteger.valueOf(toLong)
196+
def toJavaBigInteger: java.math.BigInteger = {
197+
if (decimalVal.ne(null)) {
198+
decimalVal.underlying().toBigInteger()
199+
} else {
200+
java.math.BigInteger.valueOf(toLong)
201+
}
202+
}
191203

192204
def toUnscaledLong: Long = {
193205
if (decimalVal.ne(null)) {

sql/catalyst/src/test/scala/org/apache/spark/sql/types/DecimalSuite.scala

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,4 +228,15 @@ class DecimalSuite extends SparkFunSuite with PrivateMethodTester {
228228
val decimal = Decimal.apply(bigInt)
229229
assert(decimal.toJavaBigDecimal.unscaledValue.toString === "9223372036854775808")
230230
}
231+
232+
test("SPARK-26038: toScalaBigInt/toJavaBigInteger") {
233+
// not fitting long
234+
val decimal = Decimal("1234568790123456789012348790.1234879012345678901234568790")
235+
assert(decimal.toScalaBigInt == scala.math.BigInt("1234568790123456789012348790"))
236+
assert(decimal.toJavaBigInteger == new java.math.BigInteger("1234568790123456789012348790"))
237+
// fitting long
238+
val decimalLong = Decimal(123456789123456789L, 18, 9)
239+
assert(decimalLong.toScalaBigInt == scala.math.BigInt("123456789"))
240+
assert(decimalLong.toJavaBigInteger == new java.math.BigInteger("123456789"))
241+
}
231242
}

0 commit comments

Comments
 (0)