How to pad a number with zeros in Go

It is sometimes necessary to pad a number with zeros to ensure a minumum width. For example, if you want a width of at least four digits the number 9 becomes “0009”, the number 10 becomes “0010”, and so on. The fmt package can do this for you:

func main() {
	var numbers = []int{1, 10, 100, 345, 1280}
	for _, v := range numbers {
		fmt.Printf("%04d\n", v)
Run code snippet on the Go playground

The presence of %04d is what causes the value to be printed with a width of 4 and the 0 as the padding character. If the provided value has four or more digits, the value will be printed as is without being padded.

If you don’t want to return a string for later use instead of printing to the standard output, use fmt.Sprintf instead:

s := fmt.Sprintf("%04d", 45)
fmt.Println(s) // 0045

Thanks for reading, and happy coding!