Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix incorrect calculation of decimal modulo #258

Merged
merged 1 commit into from
Oct 21, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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