2

I would like to format a big int as a string with leading zeros. I'm looking for an example similar to this, but with Big:

I'm looking at source here.

But when I call:

m := big.NewInt(99999999999999)
fmt.Println(m.Format("%010000000000000000000","d"))

I see:

prog.go:10:22: m.Format("%010000000000000000000", "d") used as value
prog.go:10:23: cannot use "%010000000000000000000" (type string) as type fmt.State in argument to m.Format:
    string does not implement fmt.State (missing Flag method)
prog.go:10:48: cannot use "d" (type string) as type rune in argument to m.Format

(I understand normally I can use m.String(), but zero padding seems to complicate this, so I'm looking specifically for some help on the Format method.)

Here's my playground link.

icza
  • 289,344
  • 42
  • 658
  • 630
Mittenchops
  • 15,641
  • 28
  • 103
  • 200

2 Answers2

2

You can simply use fmt.Sprintf(...) with the "%020s" directive (where 20 is whatever total length you want). The s verb will use the natural string format of the big int and the 020 modifier will create a string with total length of (at least) 20 with zero padding (instead of whitespace).

For example (Go Playground):

m := big.NewInt(99999999999999)
s := fmt.Sprintf("%020s", m)
fmt.Println(s)
// 00000099999999999999
maerics
  • 133,300
  • 39
  • 246
  • 273
1

The Int.Format() is not for you to call manually (although you could), but it is to implement fmt.Formatter so the fmt package will support formatting big.Int values out-of-the box.

See this example:

m := big.NewInt(99)
fmt.Printf("%06d\n", m)

if _, ok := m.SetString("1234567890123456789012345678901234567890", 10); !ok {
    panic("big")
}
fmt.Printf("%060d\n", m)

Outputs (try it on the Go Playground):

000099
000000000000000000001234567890123456789012345678901234567890

This is the simplest, so use this. Manually creating an fmt.Formatter gives you more control, but is also harder to do it. Unless this is a performance critical part of your app, just use the above solution.

icza
  • 289,344
  • 42
  • 658
  • 630
  • I would like to store the string, not print it. – Mittenchops Oct 01 '18 at 17:18
  • @Mittenchops You didn't mention that in your question, and the example you provided also prints to the console. Everything I wrote in the answer still applies, you just have to use `fmt.Sprintf()` instead of `fmt.Printf()`. For more details, see [Format a Go string without printing?](https://stackoverflow.com/questions/11123865/format-a-go-string-without-printing/31742265#31742265) – icza Oct 01 '18 at 17:39