skaldesh
skaldesh

Reputation: 1530

golang format leading zeros with sign

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?

Upvotes: 6

Views: 5320

Answers (1)

peterSO
peterSO

Reputation: 166596

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

Upvotes: 8

Related Questions