DEV Community

Tyler Smith
Tyler Smith

Posted on • Edited on

3 1

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!

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay