diff --git a/decimal.go b/decimal.go index fd54cb5..17c8d72 100644 --- a/decimal.go +++ b/decimal.go @@ -828,6 +828,23 @@ func Max(first Decimal, rest ...Decimal) Decimal { return ans } +// Sum returns the combined total of the provided first and rest Decimals +func Sum(first Decimal, rest ...Decimal) Decimal { + total := first + for _, item := range rest { + total = total.Add(item) + } + + return total +} + +// Avg returns the average value of the provided first and rest Decimals +func Avg(first Decimal, rest ...Decimal) Decimal { + count := New(int64(len(rest)+1), 0) + sum := Sum(first, rest...) + return sum.Div(count) +} + func min(x, y int32) int32 { if x >= y { return y diff --git a/decimal_test.go b/decimal_test.go index 94d0db7..fc9cb12 100644 --- a/decimal_test.go +++ b/decimal_test.go @@ -1654,7 +1654,7 @@ func TestNullDecimal_Value(t *testing.T) { } func TestBinary(t *testing.T) { - for x, _ := range testTable { + for x := range testTable { // Create the decimal d1 := NewFromFloat(x) @@ -1689,7 +1689,7 @@ func slicesEqual(a, b []byte) bool { } func TestGobEncode(t *testing.T) { - for x, _ := range testTable { + for x := range testTable { d1 := NewFromFloat(x) b1, err := d1.GobEncode() @@ -1730,3 +1730,33 @@ func TestGobEncode(t *testing.T) { } } } + +func TestSum(t *testing.T) { + vals := make([]Decimal, 10) + var i = int64(0) + + for key := range vals { + vals[key] = New(i, 0) + i++ + } + + sum := Sum(vals[0], vals[1:]...) + if !sum.Equal(New(45, 0)) { + t.Errorf("Failed to calculate sum, expected %s got %s", New(45, 0), sum) + } +} + +func TestAvg(t *testing.T) { + vals := make([]Decimal, 10) + var i = int64(0) + + for key := range vals { + vals[key] = New(i, 0) + i++ + } + + avg := Avg(vals[0], vals[1:]...) + if !avg.Equal(NewFromFloat(4.5)) { + t.Errorf("Failed to calculate average, expected %s got %s", NewFromFloat(4.5).String(), avg.String()) + } +}