Home > Mobile >  How to get a float result from a HELM template division operation?
How to get a float result from a HELM template division operation?

Time:11-13

In helm, there are Math functions https://helm.sh/docs/chart_template_guide/function_list/#math-functions and they have a div function which divides integer! but is there any way to get a decimal result out of division?

I need to get a unit interval out of the percentage.

So if the value is 90 I need to get 0.9, if it is 2 I need 0.02.

Thanks

CodePudding user response:

Unfortunately there are no functions available in Helm templates which support floating point division.

Easiest would be to register a custom function which does the conversion and division.

If you can't register your custom functions, there is still a way to do this with what's available in Help templates.

You may construct a string that contains the floating point representation of the expected result, and use the float64 Helm template function to parse that string into a float64 value.

Here's how it may look like:

{{ printf "%d.d" (div . 100) (mod . 100) | float64 }}

If the percent is 100, the first digit will be 1, 0 otherwise. Then follows a dot and the 2-digit value of the percent, so using this format string, you'll get the floating point representation. Passing this to the float64 function, it'll parse it and return it as a float64 value.

Testing it:

    t := template.Must(template.New("").Funcs(template.FuncMap{
        "div":     func(a, b int) int { return a / b },
        "mod":     func(a, b int) int { return a % b },
        "float64": func(s string) (float64, error) { return strconv.ParseFloat(s, 64) },
    }).Parse(`{{range .}}{{ printf "%d.d" (div . 100) (mod . 100) | float64 }}
{{end}}`))

    if err := t.Execute(os.Stdout, []int{0, 2, 90, 100}); err != nil {
        panic(err)
    }

Output (try it on the Go Playground):

0
0.02
0.9
1
  • Related