1

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".

Milliorn
  • 175
  • 2
  • 3
  • 13
  • 1
    Does this answer your question? [Golang: How to pad a number with zeros when printing?](https://stackoverflow.com/questions/25637440/golang-how-to-pad-a-number-with-zeros-when-printing) – Grokify Aug 06 '21 at 15:46

3 Answers3

6

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)
}

https://golang.org/pkg/fmt/

See other flags in the docs - pad with leading zeros rather than spaces

https://play.golang.org/p/0EM4aE2Hk6H

Kenny Grant
  • 9,360
  • 2
  • 33
  • 47
2

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
}
Burak Serdar
  • 46,455
  • 3
  • 40
  • 59
0

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
}

Run this code on the Golang Playground!