How to Pad a Number with Zeros in Go
Zero-padding numbers to a specific width is a common task, especially for formatting purposes. For instances where a minimum width of four digits is required, single-digit numbers transform accordingly: 9 becomes “0009”, 10 becomes “0010”, and so forth.
This functionality is readily provided by the fmt
package in Go, as
illustrated below:
func main() {
var numbers = []int{1, 10, 100, 345, 1280}
for _, v := range numbers {
fmt.Printf("%04d\n", v)
}
}
0001
0010
0100
0345
1280
The %04d
specifier in the format string ensures that numbers are printed to a
width of 4, using 0 as the padding character. Numbers with four or more digits
are displayed as they are, without additional padding.
Thanks for reading, and happy coding!