Skip to content

Commit

Permalink
Fix incorrect calculation of decimal modulo (#258)
Browse files Browse the repository at this point in the history
  • Loading branch information
mwoss authored Oct 21, 2021
1 parent 683f5e1 commit fa3b22f
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 10 deletions.
4 changes: 2 additions & 2 deletions decimal.go
Original file line number Diff line number Diff line change
Expand Up @@ -552,7 +552,7 @@ func (d Decimal) Div(d2 Decimal) Decimal {
return d.DivRound(d2, int32(DivisionPrecision))
}

// QuoRem does divsion with remainder
// QuoRem does division with remainder
// d.QuoRem(d2,precision) returns quotient q and remainder r such that
// d = d2 * q + r, q an integer multiple of 10^(-precision)
// 0 <= r < abs(d2) * 10 ^(-precision) if d>=0
Expand Down Expand Up @@ -628,7 +628,7 @@ func (d Decimal) DivRound(d2 Decimal, precision int32) Decimal {

// Mod returns d % d2.
func (d Decimal) Mod(d2 Decimal) Decimal {
quo := d.Div(d2).Truncate(0)
quo := d.DivRound(d2, -d.exp+1).Truncate(0)
return d.Sub(d2.Mul(quo))
}

Expand Down
20 changes: 12 additions & 8 deletions decimal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2131,14 +2131,18 @@ func TestDecimal_Mod(t *testing.T) {
}

inputs := map[Inp]string{
Inp{"3", "2"}: "1",
Inp{"3451204593", "2454495034"}: "996709559",
Inp{"24544.95034", ".3451204593"}: "0.3283950433",
Inp{".1", ".1"}: "0",
Inp{"0", "1.001"}: "0",
Inp{"-7.5", "2"}: "-1.5",
Inp{"7.5", "-2"}: "1.5",
Inp{"-7.5", "-2"}: "-1.5",
Inp{"3", "2"}: "1",
Inp{"3451204593", "2454495034"}: "996709559",
Inp{"9999999999", "1275"}: "324",
Inp{"9999999999.9999998", "1275.49"}: "239.2399998",
Inp{"24544.95034", "0.3451204593"}: "0.3283950433",
Inp{"0.499999999999999999", "0.25"}: "0.249999999999999999",
Inp{"0.989512958912895912", "0.000001"}: "0.000000958912895912",
Inp{"0.1", "0.1"}: "0",
Inp{"0", "1.001"}: "0",
Inp{"-7.5", "2"}: "-1.5",
Inp{"7.5", "-2"}: "1.5",
Inp{"-7.5", "-2"}: "-1.5",
}

for inp, res := range inputs {
Expand Down

0 comments on commit fa3b22f

Please sign in to comment.