How can I format an int in go to make sure there is always two digits?
For example, 1 would be formatted to 01
.
Another option:
package main
import (
"golang.org/x/text/language"
"golang.org/x/text/message"
"golang.org/x/text/number"
)
var fmt = message.NewPrinter(language.English)
func main() {
n := number.Decimal(
1, number.Pad('0'), number.FormatWidth(2),
)
fmt.Println(n)
}
https://pkg.go.dev/golang.org/x/text/number
You can use fmt.Printf()
or fmt.Sprintf()
to create a string with left-padded zeroes. fmt.Printf()
will print the data while fmt.Sprintf()
will allow you to assign the resulting string to a variable.
Here are the signatures from the docs:
func Printf(format string, a ...interface{}) (n int, err error)
func Sprintf(format string, a ...interface{}) string
For example:
// Printing directly using fmt.Printf()
fmt.Printf("%02d\n", 1)
// With output assignment
count, err := fmt.Printf("%02d\n", 1)
if err == nil {
fmt.Printf("Printed %v bytes\n", count)
} else {
fmt.Println("Error printing")
}
// Assigning to variable using fmt.Sprintf()
formatted := fmt.Sprintf("%02d", 1)
fmt.Println(formatted)
Docs: https://golang.org/pkg/fmt/
You should take a look at the fmt.Printf
documentation. It explains all of the formatting flags. The specific ones you are looking for are 0
and 2
. 0
indicates that you want to pad the number to the specified width with leading zeros. 2
indicates the width that you want, these two flags together will pad single digits with a leading 0, but ignore numbers that are 2 digits in length or greater.
package main
import "fmt"
func main() {
for i := 1; i <= 10; i++ {
fmt.Printf("%02d\n", i)
}
}
outputs:
01
02
03
04
05
06
07
08
09
10
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