DEV Community


Casting integers to floats for float division in Hugo

raspberrytyler profile image Tyler Smith ・1 min read

I recently needed to do float division on two integers in a site I built with the Hugo static site generator.

Normally if you divide two integers in Hugo, it will give you integer division.

For example, if you calculate 5 / 2 with integer division, it will give you a result of 2 instead of 2.5. This is Hugo's default behavior, because both 5 and 2 are integers.

Integer division:

{{- $num1 := 5 -}}
{{- $num2 := 2 -}}
{{div $num1 $num2}}

{{/* Yields result of 2 */}}

In order to do float division in Hugo (or what my high school math teacher would consider normal division), at least one of the numbers you're dividing must be a float.

The easiest way to do this is to cast all the numbers you're using in your calculation as floats when you're declaring your variables.

Float division:

{{- $num1 := float 5 -}}
{{- $num2 := float 2 -}}
{{div $num1 $num2}}

{{/* Yields result of 2.5 */}}

This will make Hugo use float division and yield 2.5 as a result.

I hope this helps!

Discussion (0)

Editor guide