Golang : Print leading(padding) zero or spaces in fmt.Printf?
Problem :
You want to include leading zero or spaces in front(prefix) of integer when printing out with fmt.Println()
or fmt.Printf()
functions. How to do that?
Solution :
From https://golang.org/pkg/fmt/ - Other flags:
+
always print a sign for numeric values; guarantee ASCII-only output for %q (%+q)
-
pad with spaces on the right rather than the left (left-justify the field)
#
alternate format: add leading 0 for octal (%#o), 0x for hex (%#x);0X for hex (%#X); suppress 0x for %p (%#p); for %q, print a raw (backquoted) string if strconv.CanBackquote returns true; write e.g. U+0078 'x' if the character is printable for %U (%#U).
' '
(space) leave a space for elided sign in numbers (% d); put spaces between bytes printing strings or slices in hex (% x, % X)
0
pad with leading zeros rather than spaces; for numbers, this moves the padding after the sign
Code example :
package main
import "fmt"
func main() {
// you want to display 000108 (length = 6)
// pad zero to total length of 6
// d
fmt.Printf("Leading or padded with zero : |%06d|\n", 108)
// pad spaces in front(prefix)
fmt.Printf("Leading or padded with space : |%6d|\n", 108)
}
Output :
Leading or padded with zero : |000108|
Leading or padded with space : | 108|
References :
http://stackoverflow.com/questions/153890/printing-leading-0s-in-c
See also : Golang : Convert octal value to string to deal with leading zero problem
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+9.2k Golang : Qt Yes No and Quit message box example
+7.2k Golang : Hue, Saturation and Value(HSV) with OpenCV example
+12.8k Golang : Convert(cast) uintptr to string example
+31.9k Golang : Math pow(the power of x^y) example
+11.1k Golang : Post data with url.Values{}
+16.8k Golang : Covert map/slice/array to JSON or XML format
+17.8k Golang : Check if a directory exist or not
+18.2k Golang : Get download file size
+22.6k Golang : Calculate time different
+14.7k Golang : package is not in GOROOT during compilation
+25.5k Golang : How to write CSV data to file
+10.3k Golang : Select region of interest with mouse click and crop from image