DEV Community

Tyler Smith
Tyler Smith

Posted on • Updated on

Casting integers to floats for float division in Hugo

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 */}}
Enter fullscreen mode Exit fullscreen mode

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 */}}
Enter fullscreen mode Exit fullscreen mode

You can also cast them at the time of using them.

Float division:

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

{{/* Yields result of 2.5 */}}
Enter fullscreen mode Exit fullscreen mode

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

I hope this helps!

Discussion (0)