Format numbers with a leading zero

This is more a quick tip than a huge article. Often you need numbers below 10 with a leading zero like 03 instead of 3. This can be achieved easily with Hugo's printf method.

With printf you can format a string or even a number with various verbs described in the official documentation of Go.

Assume we have a number 5 and a number 12 and the expected output should be 05 and 12 to have the same amount of digits. This is necessary for formatting dates.

Instead of checking if the number is below 10 and prefix the number with a 0 we can easily use:

{{ $number := 5 }}
{{ printf "%02d" $number }} -> 05

But if we rather like to use 5 digits for example an invoice number we can just use %05d since the number before the letter d is the variable for how many 0 we want to fill up. Like:

{{ $invoice := 453 }}
{{ printf "%05d" $invoice }} -> 00453

As I told you. Quick-Read! Easy to understand :-)