I came up with a way to pad leading zeros into a Go string. I'm not sure if this is the way you do this in Go. Is there a proper way to do this in Go? This is what I came up with and can be found inside the second if block. I tried Google to see if it had something built in without luck.
func integerToStringOfFixedWidth(n int, w int) string {
s := strconv.Itoa(n)
l := len(s)
if l < w {
for i := l; i < w; i++ {
s = "0" + s
}
return s
}
if l > w {
return s[l-w:]
}
return s
}
For n = 1234 and w = 5, the output should be integerToStringOfFixedWidth(n, w) = "01234".
You can use Sprintf/Printf for that (Use Sprintf with the same format to print to a string):
package main
import (
"fmt"
)
func main() {
// For fixed width
fmt.Printf("%05d", 4)
// Or if you need variable widths:
fmt.Printf("%0*d", 5, 1234)
}
See other flags in the docs - pad with leading zeros rather than spaces
You can do something like this:
func integerToStringOfFixedWidth(n, w int) string {
s := fmt.Sprintf(fmt.Sprintf("%%0%dd", w), n)
l := len(s)
if l > w {
return s[l-w:]
}
return s
}
Use a well documented and tested package instead of writing your own paddig code. Here's how to use github.com/keltia/leftpad:
func integerToStringOfFixedWidth(n int, w int) string {
s, _ := leftpad.PadChar(strconv.Itoa(n), w, '0')
return s
}