From e67d189b993faa45de2ce069dbd0037c56362c19 Mon Sep 17 00:00:00 2001 From: "willem.romijn" Date: Mon, 13 Jan 2025 09:41:54 +0100 Subject: [PATCH] poc - failing tests --- .../src/main/kotlin/com/alliander/open/measure/Measure.kt | 7 +++++-- .../test/kotlin/com/alliander/open/measure/MeasureTest.kt | 7 ++++++- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/measure/src/main/kotlin/com/alliander/open/measure/Measure.kt b/measure/src/main/kotlin/com/alliander/open/measure/Measure.kt index 52c5d88..2f12d23 100644 --- a/measure/src/main/kotlin/com/alliander/open/measure/Measure.kt +++ b/measure/src/main/kotlin/com/alliander/open/measure/Measure.kt @@ -43,7 +43,10 @@ data class Measure(val amount: BigDecimal, val units: U) : Comparable infix fun `in`(other: A): BigDecimal = if (units == other) amount - else (amount * units.ratio).divide(other.ratio, amount.scale() + other.ratio.precision(), RoundingMode.UP) + else { + val result = (amount * units.ratio).divide(other.ratio) + result.setScale(amount.precision() - result.precision() + result.scale(), RoundingMode.UP) + } operator fun plus(other: Measure): Measure = baseUnits( units, @@ -121,4 +124,4 @@ data class Measure(val amount: BigDecimal, val units: U) : Comparable } private fun BigDecimal.roundToMultiple(factor: BigDecimal, roundingMode: RoundingMode): BigDecimal = - this.divide(factor, 0, roundingMode) * factor + this.divide(factor, 0, roundingMode) * factor diff --git a/measure/src/test/kotlin/com/alliander/open/measure/MeasureTest.kt b/measure/src/test/kotlin/com/alliander/open/measure/MeasureTest.kt index 5c20c08..8ff52ad 100644 --- a/measure/src/test/kotlin/com/alliander/open/measure/MeasureTest.kt +++ b/measure/src/test/kotlin/com/alliander/open/measure/MeasureTest.kt @@ -24,6 +24,7 @@ import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe import io.kotest.property.checkAll import java.math.BigDecimal +import java.math.RoundingMode.HALF_UP import java.math.RoundingMode.UP class MeasureTest : StringSpec({ @@ -222,6 +223,10 @@ class MeasureTest : StringSpec({ "Unit conversion uses the correct scale" { val energyInJoule = 13500000 * joule val valueInKwh = energyInJoule `in` kiloWattHour - valueInKwh.stripTrailingZeros() shouldBe BigDecimal.valueOf(3.75) + valueInKwh shouldBe BigDecimal.valueOf(3.75).setScale(7) + + val energyInKwh = 3.75 * kiloWattHour + val valueInJoule = energyInKwh `in` joule + valueInJoule shouldBe BigDecimal.valueOf(1.35E+7) } })