Skip to content

Commit

Permalink
Merge pull request #315 from ionspin/fix-rounding-error-when-dividing
Browse files Browse the repository at this point in the history
Fix invalid rounding
  • Loading branch information
ionspin authored Oct 25, 2024
2 parents 83d308e + c1bf3b4 commit e2ec790
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -1289,16 +1289,17 @@ class BigDecimal private constructor(
newExponent--
}
val exponentModifier = result.numberOfDecimalDigits() - resolvedDecimalMode.decimalPrecision
val discarded = divRem.remainder * other.significand

return if (usingScale) {
BigDecimal(
roundDiscarded(result, divRem.remainder, resolvedDecimalMode),
roundDiscarded(result, discarded, resolvedDecimalMode),
newExponent + exponentModifier,
resolvedDecimalMode.copy(decimalPrecision = result.numberOfDecimalDigits())
)
} else {
BigDecimal(
roundDiscarded(result, divRem.remainder, resolvedDecimalMode),
roundDiscarded(result, discarded, resolvedDecimalMode),
newExponent + exponentModifier,
resolvedDecimalMode
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -352,4 +352,12 @@ class ReportedIssueReplicationTest {
rounded
)
}

@Test
fun roundHalfAway() {
val result = BigDecimal.fromInt(2)
.divide(BigDecimal.fromInt(3), DecimalMode(2, RoundingMode.ROUND_HALF_AWAY_FROM_ZERO))
.doubleValue(false)
assertEquals(0.67f, result.toFloat())
}
}

0 comments on commit e2ec790

Please sign in to comment.