Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang format leading zeros with sign

Tags:

formatting

go

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?

like image 603
skaldesh Avatar asked Dec 07 '17 11:12

skaldesh


People also ask

How do I pad a string in Golang?

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.

What is FMT go?

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.

How to format strings in Go?

To format strings in Go, we use functions including fmt. Printf , fmt. Sprintf , or fmt. Fscanf .


1 Answers

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
like image 131
peterSO Avatar answered Oct 18 '22 05:10

peterSO