Implement Modulus arithmetic function

This commit is contained in:
Nathan VanBenschoten 2016-01-15 16:32:48 -05:00
parent af95951b3f
commit ecd4a8353a
2 changed files with 39 additions and 0 deletions

View file

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

View file

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