Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go - How to format number digit count [duplicate]

Tags:

go

How can I format an int in go to make sure there is always two digits? For example, 1 would be formatted to 01.

like image 901
AlexB Avatar asked Jun 20 '15 16:06

AlexB


3 Answers

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

like image 98
Zombo Avatar answered Nov 19 '22 04:11

Zombo


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/

like image 43
Grokify Avatar answered Nov 19 '22 05:11

Grokify


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
like image 7
Hunter McMillen Avatar answered Nov 19 '22 04:11

Hunter McMillen