Golang 中 Big Ints 前导零填充的 Format 方法的使用示例

Usage example for Format method with leading zero padding for Big Ints in Golang

我想将大整数格式化为带前导零的字符串。我正在寻找一个类似于 this 的示例,但具有 Big:

我正在查看来源 here

但是当我打电话时:

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

我明白了:

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

(我知道通常我可以使用 m.String(),但零填充似乎使这个复杂化,所以我正在寻找有关 Format 方法的一些帮助。)

这里是my playground link

开箱即用的 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 值。

看这个例子:

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

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

输出(在 Go Playground 上尝试):

000099
000000000000000000001234567890123456789012345678901234567890

这个最简单,就用这个吧。手动创建 fmt.Formatter 可以让您有更多的控制权,但也更难做到。除非这是您应用程序的性能关键部分,否则只需使用上述解决方案即可。

您可以简单地使用 fmt.Sprintf(...)"%020s" 指令(其中 20 是您想要的任何总长度)。 s 动词将使用 big int 的自然字符串格式,而 020 修饰符将创建一个总长度(至少)20 的字符串,并使用零填充(而不是空格)。

例如 (Go Playground):

m := big.NewInt(99999999999999)
s := fmt.Sprintf("%020s", m)
fmt.Println(s)
// 00000099999999999999