From fa3b22f4d484d626ee81919285cf3d22ad3a4000 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20Wo=C5=9B?= Date: Thu, 21 Oct 2021 11:22:23 +0200 Subject: [PATCH] Fix incorrect calculation of decimal modulo (#258) --- decimal.go | 4 ++-- decimal_test.go | 20 ++++++++++++-------- 2 files changed, 14 insertions(+), 10 deletions(-) diff --git a/decimal.go b/decimal.go index 84405ec1..c614ea79 100644 --- a/decimal.go +++ b/decimal.go @@ -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)) } diff --git a/decimal_test.go b/decimal_test.go index cd7f00b1..2b3a99e1 100644 --- a/decimal_test.go +++ b/decimal_test.go @@ -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 {