Fix incorrect calculation of decimal modulo (#258)

This commit is contained in:
Mateusz Woś 2021-10-21 11:22:23 +02:00 committed by GitHub
parent 683f5e1a7e
commit fa3b22f4d4
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 14 additions and 10 deletions

View file

@ -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
@ -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))
}

View file

@ -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 {