From 5b5f1056df87e9dce7822179cf49b2b4579ae306 Mon Sep 17 00:00:00 2001 From: Ev Dolzhenko Date: Mon, 7 Jul 2025 17:12:06 +0300 Subject: [PATCH] Add abs and absf math functions --- docs/math.md | 10 ++++++++++ docs/mathf.md | 10 ++++++++++ functions.go | 2 ++ numeric.go | 15 ++++++++++++++- numeric_test.go | 14 ++++++++++++++ 5 files changed, 50 insertions(+), 1 deletion(-) diff --git a/docs/math.md b/docs/math.md index b08d0a2f..b15f186c 100644 --- a/docs/math.md +++ b/docs/math.md @@ -34,6 +34,16 @@ Multiply with `mul`. Accepts two or more inputs. mul 1 2 3 ``` +## abs + +Return the absolute value of an integer. + +This will return `3`: + +``` +abs -3 +``` + ## max Return the largest of a series of integers: diff --git a/docs/mathf.md b/docs/mathf.md index 759c8525..0fa4a2e9 100644 --- a/docs/mathf.md +++ b/docs/mathf.md @@ -65,3 +65,13 @@ This will return `1.5`: ``` minf 1.5 2 3 ``` + +## absf + +Return the absolute value of a float. + +This will return `3.14`: + +``` +absf -3.14 +``` diff --git a/functions.go b/functions.go index cda47d26..6e621b59 100644 --- a/functions.go +++ b/functions.go @@ -229,6 +229,8 @@ var genericMap = map[string]interface{}{ "min": min, "maxf": maxf, "minf": minf, + "abs": abs, + "absf": absf, "ceil": ceil, "floor": floor, "round": round, diff --git a/numeric.go b/numeric.go index f68e4182..ab6a434a 100644 --- a/numeric.go +++ b/numeric.go @@ -6,8 +6,8 @@ import ( "strconv" "strings" - "github.com/spf13/cast" "github.com/shopspring/decimal" + "github.com/spf13/cast" ) // toFloat64 converts 64-bit floats @@ -64,6 +64,19 @@ func minf(a interface{}, i ...interface{}) float64 { return aa } +func abs(a interface{}) int64 { + aa := toInt64(a) + if aa < 0 { + return -aa + } + return aa +} + +func absf(a interface{}) float64 { + aa := toFloat64(a) + return math.Abs(aa) +} + func until(count int) []int { step := 1 if count < 0 { diff --git a/numeric_test.go b/numeric_test.go index 1252cd73..e54afb4f 100644 --- a/numeric_test.go +++ b/numeric_test.go @@ -277,6 +277,20 @@ func TestSubf(t *testing.T) { } } +func TestAbs(t *testing.T) { + tpl := `{{ abs -3 }}` + if err := runt(tpl, `3`); err != nil { + t.Error(err) + } +} + +func TestAbsf(t *testing.T) { + tpl := `{{ absf -3.4 }}` + if err := runt(tpl, `3.4`); err != nil { + t.Error(err) + } +} + func TestCeil(t *testing.T) { assert.Equal(t, 123.0, ceil(123)) assert.Equal(t, 123.0, ceil("123"))