Skip to content

Commit

Permalink
Added ceil floor and round functions
Browse files Browse the repository at this point in the history
  • Loading branch information
alanquillin committed May 26, 2017
1 parent 2f4371a commit 86d326a
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 0 deletions.
3 changes: 3 additions & 0 deletions functions.go
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,9 @@ var genericMap = map[string]interface{}{
"biggest": max,
"max": max,
"min": min,
"ceil": ceil,
"floor": floor,
"round": round,

// string slices. Note that we reverse the order b/c that's better
// for template processing.
Expand Down
30 changes: 30 additions & 0 deletions numeric.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,3 +127,33 @@ func untilStep(start, stop, step int) []int {
}
return v
}

func floor(a interface{}) float64 {
aa := toFloat64(a)
return math.Floor(aa)
}

func ceil(a interface{}) float64 {
aa := toFloat64(a)
return math.Ceil(aa)
}

func round(a interface{}, p int, r_opt ...float64) float64 {
roundOn := .5
if len(r_opt) > 0 {
roundOn = r_opt[0]
}
val := toFloat64(a)
places := toFloat64(p)

var round float64
pow := math.Pow(10, places)
digit := pow * val
_, div := math.Modf(digit)
if div >= roundOn {
round = math.Ceil(digit)
} else {
round = math.Floor(digit)
}
return round / pow
}
25 changes: 25 additions & 0 deletions numeric_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package sprig

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestUntil(t *testing.T) {
Expand Down Expand Up @@ -178,3 +180,26 @@ func TestMul(t *testing.T) {
t.Error(err)
}
}

func TestCeil(t *testing.T){
assert.Equal(t, 123.0, ceil(123))
assert.Equal(t, 123.0, ceil("123"))
assert.Equal(t, 124.0, ceil(123.01))
assert.Equal(t, 124.0, ceil("123.01"))
}

func TestFloor(t *testing.T){
assert.Equal(t, 123.0, floor(123))
assert.Equal(t, 123.0, floor("123"))
assert.Equal(t, 123.0, floor(123.9999))
assert.Equal(t, 123.0, floor("123.9999"))
}

func TestRound(t *testing.T){
assert.Equal(t, 123.556, round(123.5555, 3))
assert.Equal(t, 123.556, round("123.55555", 3))
assert.Equal(t, 124.0, round(123.500001, 0))
assert.Equal(t, 123.0, round(123.49999999, 0))
assert.Equal(t, 123.23, round(123.2329999, 2, .3))
assert.Equal(t, 123.24, round(123.233, 2, .3))
}

0 comments on commit 86d326a

Please sign in to comment.