Skip to content

Commit fa3b22f

Browse files
authored
Fix incorrect calculation of decimal modulo (#258)
1 parent 683f5e1 commit fa3b22f

File tree

2 files changed

+14
-10
lines changed

2 files changed

+14
-10
lines changed

decimal.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -552,7 +552,7 @@ func (d Decimal) Div(d2 Decimal) Decimal {
552552
return d.DivRound(d2, int32(DivisionPrecision))
553553
}
554554

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

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

decimal_test.go

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2131,14 +2131,18 @@ func TestDecimal_Mod(t *testing.T) {
21312131
}
21322132

21332133
inputs := map[Inp]string{
2134-
Inp{"3", "2"}: "1",
2135-
Inp{"3451204593", "2454495034"}: "996709559",
2136-
Inp{"24544.95034", ".3451204593"}: "0.3283950433",
2137-
Inp{".1", ".1"}: "0",
2138-
Inp{"0", "1.001"}: "0",
2139-
Inp{"-7.5", "2"}: "-1.5",
2140-
Inp{"7.5", "-2"}: "1.5",
2141-
Inp{"-7.5", "-2"}: "-1.5",
2134+
Inp{"3", "2"}: "1",
2135+
Inp{"3451204593", "2454495034"}: "996709559",
2136+
Inp{"9999999999", "1275"}: "324",
2137+
Inp{"9999999999.9999998", "1275.49"}: "239.2399998",
2138+
Inp{"24544.95034", "0.3451204593"}: "0.3283950433",
2139+
Inp{"0.499999999999999999", "0.25"}: "0.249999999999999999",
2140+
Inp{"0.989512958912895912", "0.000001"}: "0.000000958912895912",
2141+
Inp{"0.1", "0.1"}: "0",
2142+
Inp{"0", "1.001"}: "0",
2143+
Inp{"-7.5", "2"}: "-1.5",
2144+
Inp{"7.5", "-2"}: "1.5",
2145+
Inp{"-7.5", "-2"}: "-1.5",
21422146
}
21432147

21442148
for inp, res := range inputs {

0 commit comments

Comments
 (0)