I'd like to format an integer to an UTC offset formatted string
I tried it using the fmt package:
fmt.Sprintf("%+02d:00", utc)
When utc is 1, I'd like it to print "+01:00", but I get "+1:00"
How can I combine the leading zeros flag, the sign flag and the width in one format string?
In Go (Golang) you can use the fmt package to add padding to your strings. You can use the width option as defined in the fmt package. You can also define the padding width using a asterisk and specifying a parameter representing the length of the padding.
fmt stands for the Format package. This package allows to format basic strings, values, or anything and print them or collect user input from the console, or write into a file using a writer or even print customized fancy error messages. This package is all about formatting input and output.
To format strings in Go, we use functions including fmt. Printf , fmt. Sprintf , or fmt. Fscanf .
width is the minimum number of runes to output
+01
is minimum width 3
. For example,
package main
import (
"fmt"
)
func main() {
utc := 1
s := fmt.Sprintf("%+03d:00", utc)
fmt.Println(s)
}
Playground: https://play.golang.org/p/Z0vBzzn-kp
Output:
+01:00
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With