diff --git a/decimal.go b/decimal.go index 0d2425f..287f2c5 100644 --- a/decimal.go +++ b/decimal.go @@ -287,6 +287,12 @@ func (d Decimal) Div(d2 Decimal) Decimal { return ret } +// Mod returns d % d2. +func (d Decimal) Mod(d2 Decimal) Decimal { + quo := d.Div(d2).Truncate(0) + return d.Sub(d2.Mul(quo)) +} + // Cmp compares the numbers represented by d and d2 and returns: // // -1 if d < d2 diff --git a/decimal_test.go b/decimal_test.go index ecfb5ad..9175622 100644 --- a/decimal_test.go +++ b/decimal_test.go @@ -685,6 +685,39 @@ func TestDecimal_Div(t *testing.T) { } } +func TestDecimal_Mod(t *testing.T) { + type Inp struct { + a string + b string + } + + 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", + } + + for inp, res := range inputs { + a, err := NewFromString(inp.a) + if err != nil { + t.FailNow() + } + b, err := NewFromString(inp.b) + if err != nil { + t.FailNow() + } + c := a.Mod(b) + if c.String() != res { + t.Errorf("expected %s, got %s", res, c.String()) + } + } +} + func TestDecimal_Overflow(t *testing.T) { if !didPanic(func() { New(1, math.MinInt32).Mul(New(1, math.MinInt32)) }) { t.Fatalf("should have gotten an overflow panic")