Skip to content

Commit e2ec790

Browse files
authored
Merge pull request #315 from ionspin/fix-rounding-error-when-dividing
Fix invalid rounding
2 parents 83d308e + c1bf3b4 commit e2ec790

File tree

2 files changed

+11
-2
lines changed

2 files changed

+11
-2
lines changed

bignum/src/commonMain/kotlin/com/ionspin/kotlin/bignum/decimal/BigDecimal.kt

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1289,16 +1289,17 @@ class BigDecimal private constructor(
12891289
newExponent--
12901290
}
12911291
val exponentModifier = result.numberOfDecimalDigits() - resolvedDecimalMode.decimalPrecision
1292+
val discarded = divRem.remainder * other.significand
12921293

12931294
return if (usingScale) {
12941295
BigDecimal(
1295-
roundDiscarded(result, divRem.remainder, resolvedDecimalMode),
1296+
roundDiscarded(result, discarded, resolvedDecimalMode),
12961297
newExponent + exponentModifier,
12971298
resolvedDecimalMode.copy(decimalPrecision = result.numberOfDecimalDigits())
12981299
)
12991300
} else {
13001301
BigDecimal(
1301-
roundDiscarded(result, divRem.remainder, resolvedDecimalMode),
1302+
roundDiscarded(result, discarded, resolvedDecimalMode),
13021303
newExponent + exponentModifier,
13031304
resolvedDecimalMode
13041305
)

bignum/src/commonTest/kotlin/com/ionspin/kotlin/bignum/decimal/ReportedIssueReplicationTest.kt

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -352,4 +352,12 @@ class ReportedIssueReplicationTest {
352352
rounded
353353
)
354354
}
355+
356+
@Test
357+
fun roundHalfAway() {
358+
val result = BigDecimal.fromInt(2)
359+
.divide(BigDecimal.fromInt(3), DecimalMode(2, RoundingMode.ROUND_HALF_AWAY_FROM_ZERO))
360+
.doubleValue(false)
361+
assertEquals(0.67f, result.toFloat())
362+
}
355363
}

0 commit comments

Comments
 (0)