mirror of
https://github.com/shopspring/decimal.git
synced 2024-11-22 20:40:48 +01:00
Merge pull request #18 from cockroachdb/nvanbenschoten/mod
Implement Modulus arithmetic function
This commit is contained in:
commit
74d668a796
2 changed files with 39 additions and 0 deletions
|
@ -287,6 +287,12 @@ func (d Decimal) Div(d2 Decimal) Decimal {
|
||||||
return ret
|
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:
|
// Cmp compares the numbers represented by d and d2 and returns:
|
||||||
//
|
//
|
||||||
// -1 if d < d2
|
// -1 if d < d2
|
||||||
|
|
|
@ -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) {
|
func TestDecimal_Overflow(t *testing.T) {
|
||||||
if !didPanic(func() { New(1, math.MinInt32).Mul(New(1, math.MinInt32)) }) {
|
if !didPanic(func() { New(1, math.MinInt32).Mul(New(1, math.MinInt32)) }) {
|
||||||
t.Fatalf("should have gotten an overflow panic")
|
t.Fatalf("should have gotten an overflow panic")
|
||||||
|
|
Loading…
Reference in a new issue