Round a float to decimal places with Hugo Shortcodes
Last updated: Jan 4, 2025
Example shortcodes for precision rounding of floats
The built-in Go math.Round function rounds to integers. So, to round a number to decimals using Hugo, you need to write a small shortcode.
The following examples all use the technique described in Round float to any precision in Go.
- A “conventional” solution uses a shortcode that is available to all pages.
- The inline examples create a rounding function with
define
.
Shortcode to round floats
This shortcode is defined in layouts/shortcodes/roundFlt.html
.
It takes two arguments:
- The number to round
- The decimal precision (default
2
)
{{ $num := (.Get 0 | float) }}
{{ $precision := default 2 (.Get 1 ) |}}
{{ $ratio := math.Pow 10 $precision }}
{{ $product := math.Product $ratio $num }}
{{ div (math.Round $product) $ratio }}
Example call:
- 2 decimal places: {{< roundFlt 3.141592653589793238 >}}
- 5 decimal places: {{< roundFlt 3.141592653589793238 5 >}}
Renders as:
- 2 decimal places (default): 3.14
- 5 decimal places: 3.14159
Inline shortcodes scoped to one block
If you want to scope the shortcode to a page, you can use inline shortcodes with the same logic from the preceding section. However, inline shortcodes cannot have nested shortcodes. If you want to use the rounding function within more shortcode logic, you can use the template and define functions.
Besides showing another technique, I include these because inline shortcodes have interesting use cases for pages that involve numerical analysis and presentation—for examples, read Hugo inline spreadsheets.
Fixed precision
The least complex method keeps precision fixed to a certain number—in this case, 4.
{{ $precision := 4 }}
{{ define "rnd" }}
{{ $ratio := math.Pow 10 4 }}
{{ $product := math.Product $ratio . }}
{{ div (math.Round $product) $ratio }}
{{ end }}
Pi rounded to {{ $precision }} digits:
{{ template "rnd" math.Pi }}
Renders as:
Pi rounded to 4 digits:
3.1416
Variable precision
If you want variable precision, you can put the value and precision in a dict. This is more verbose than the other examples.
{{ define "rnd" }}
{{ $num := .val }}
{{ $pow := default 2 .precision }}
{{ $ratio := math.Pow 10 $pow }}
{{ $product := math.Product $ratio $num }}
{{- div (math.Round $product) $ratio }}
{{ end }}
Pi to 5 digits:
{{- template "rnd" (dict "val" math.Pi "precision" 5 ) }}
Renders as
Pi to 5 digits:
3.14159