Add math.fixed function for truncating floats

This commit is contained in:
Tobie Morgan Hitchcock 2018-04-13 20:48:48 +01:00
parent 3f7d7fc863
commit 917dbff89d
5 changed files with 27 additions and 0 deletions

View file

@ -123,6 +123,7 @@ var funcs = map[string]map[int]interface{}{
"math.ceil": {1: nil},
"math.correlation": {2: nil},
"math.covariance": {2: nil},
"math.fixed": {2: nil},
"math.floor": {1: nil},
"math.geometricmean": {1: nil},
"math.harmonicmean": {1: nil},

View file

@ -36,6 +36,12 @@ func outputFloat(val float64) (interface{}, error) {
}
}
func outputFixed(val float64, pre int64) (interface{}, error) {
out := math.Pow(10, float64(pre))
rnd := int(val*out + math.Copysign(0.5, val*out))
return float64(rnd) / out, nil
}
func ensureString(val interface{}) (out string, ok bool) {
switch val := val.(type) {
case string:

View file

@ -116,6 +116,8 @@ func Run(ctx context.Context, name string, args ...interface{}) (interface{}, er
return mathCorrelation(ctx, args...)
case "math.covariance":
return mathCovariance(ctx, args...)
case "math.fixed":
return mathFixed(ctx, args...)
case "math.floor":
return mathFloor(ctx, args...)
case "math.geometricmean":

View file

@ -54,6 +54,15 @@ func mathCovariance(ctx context.Context, args ...interface{}) (out interface{},
return outputFloat(math.Covariance(a, b))
}
func mathFixed(ctx context.Context, args ...interface{}) (out interface{}, err error) {
if val, ok := ensureFloat(args[0]); ok {
if pre, ok := ensureInt(args[1]); ok {
return outputFixed(val, pre)
}
}
return
}
func mathFloor(ctx context.Context, args ...interface{}) (out interface{}, err error) {
if val, ok := ensureFloat(args[0]); ok {
return outputFloat(math.Floor(val))

View file

@ -80,6 +80,15 @@ func TestMath(t *testing.T) {
So(res, ShouldEqual, -1)
})
Convey("math.fixed() works properly", t, func() {
res, _ = Run(context.Background(), "math.fixed", "test")
So(res, ShouldEqual, nil)
res, _ = Run(context.Background(), "math.fixed", 10, 2)
So(res, ShouldEqual, 10)
res, _ = Run(context.Background(), "math.fixed", 1.51837461, 2)
So(res, ShouldEqual, 1.52)
})
Convey("math.floor() works properly", t, func() {
res, _ = Run(context.Background(), "math.floor", "test")
So(res, ShouldEqual, nil)