Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@

package org.apache.spark.sql.types

import java.math.{MathContext, RoundingMode}

import org.apache.spark.annotation.DeveloperApi

/**
Expand Down Expand Up @@ -138,14 +136,6 @@ final class Decimal extends Ordered[Decimal] with Serializable {
}

def toBigDecimal: BigDecimal = {
if (decimalVal.ne(null)) {
decimalVal(MathContext.UNLIMITED)
} else {
BigDecimal(longVal, _scale)(MathContext.UNLIMITED)
}
}

def toLimitedBigDecimal: BigDecimal = {
if (decimalVal.ne(null)) {
decimalVal
} else {
Expand Down Expand Up @@ -273,15 +263,8 @@ final class Decimal extends Ordered[Decimal] with Serializable {

def * (that: Decimal): Decimal = Decimal(toBigDecimal * that.toBigDecimal)

def / (that: Decimal): Decimal = {
if (that.isZero) {
null
} else {
// To avoid non-terminating decimal expansion problem, we get scala's BigDecimal with limited
// precision and scala.
Decimal(toLimitedBigDecimal / that.toLimitedBigDecimal)
}
}
def / (that: Decimal): Decimal =
if (that.isZero) null else Decimal(toBigDecimal / that.toBigDecimal)

def % (that: Decimal): Decimal =
if (that.isZero) null else Decimal(toBigDecimal % that.toBigDecimal)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -171,22 +171,4 @@ class DecimalSuite extends SparkFunSuite with PrivateMethodTester {
assert(new Decimal().set(100L, 10, 0).toUnscaledLong === 100L)
assert(Decimal(Long.MaxValue, 100, 0).toUnscaledLong === Long.MaxValue)
}

test("accurate precision after multiplication") {
val decimal = (Decimal(Long.MaxValue, 38, 0) * Decimal(Long.MaxValue, 38, 0)).toJavaBigDecimal
assert(decimal.unscaledValue.toString === "85070591730234615847396907784232501249")
}

test("fix non-terminating decimal expansion problem") {
val decimal = Decimal(1.0, 10, 3) / Decimal(3.0, 10, 3)
// The difference between decimal should not be more than 0.001.
assert(decimal.toDouble - 0.333 < 0.001)
}

test("fix loss of precision/scale when doing division operation") {
val a = Decimal(2) / Decimal(3)
assert(a.toDouble < 1.0 && a.toDouble > 0.6)
val b = Decimal(1) / Decimal(8)
assert(b.toDouble === 0.125)
}
}