diff --git a/mathutil/mathutil.go b/mathutil/mathutil.go index 1c752fd..42606a8 100644 --- a/mathutil/mathutil.go +++ b/mathutil/mathutil.go @@ -24,6 +24,14 @@ func RoundPlus(f float64, precision int) float64 { return Round(f*shift) / shift } +// CeilPlus will ceil the value to the given precision. +// +// e.g. CeilPlus(123.233333, 2) will return 123.24 +func CeilPlus(f float64, precision int) float64 { + multiplier := math.Pow10(precision) + return math.Ceil(f*multiplier) / multiplier +} + // Min gets the lowest of two numbers. func Min(a, b int64) int64 { if a > b { diff --git a/mathutil/mathutil_test.go b/mathutil/mathutil_test.go index 494a77e..2305dae 100644 --- a/mathutil/mathutil_test.go +++ b/mathutil/mathutil_test.go @@ -37,6 +37,7 @@ func TestRoundPlus(t *testing.T) { {123.555555, 3, 123.556}, {123.558, 2, 123.56}, {-123.555555, 3, -123.556}, + {123.233333, 2, 123.23}, } for _, c := range cases { @@ -48,6 +49,27 @@ func TestRoundPlus(t *testing.T) { } +func TestCeilPlus(t *testing.T) { + cases := []struct { + in float64 + precision int + want float64 + }{ + {123.554999, 3, 123.555}, + {123.555555, 3, 123.556}, + {123.558, 2, 123.56}, + {-123.555555, 3, -123.555}, + {123.233333, 2, 123.24}, + } + + for _, c := range cases { + got := CeilPlus(c.in, c.precision) + if got != c.want { + t.Errorf("CeilPlus(%f) => %f, want %f", c.in, got, c.want) + } + } +} + func TestIsSignedZero(t *testing.T) { cases := []struct { in string