Home >Backend Development >Golang >How to Zero-Pad Numbers in Go Using fmt.Printf?
Zero-Padding Numeric Strings in Go
When printing integers or creating strings in a fixed width format, it can be useful to zero-pad the value to make it easier to read and compare. This can be achieved using the versatile fmt package in Go.
Problem:
How do you zero-pad a number when printing or converting it to a string to ensure a fixed width?
Solution:
The fmt package provides a convenient formatter for zero-padding numbers:
fmt.Printf("|%06d|%6d|\n", 12, 345)
Explanation:
The d format specifier indicates that the number should be printed in a field of width 6 and padded with zeros if necessary. The second argument, m, specifies a field width of 6 but does not include any padding.
Example:
Consider the following example:
package main import "fmt" func main() { fmt.Printf("|%06d|%6d|\n", 12, 345) }
Output:
|000012| 345|
As you can see, the number 12 is zero-padded to a width of 6.
Additional Resources:
The above is the detailed content of How to Zero-Pad Numbers in Go Using fmt.Printf?. For more information, please follow other related articles on the PHP Chinese website!