我想将一个大整数格式化为带有前导零的字符串。 我正在寻找一个与此类似的示例,但使用 Big:
我正在这里查看源代码。
但是当我打电话时:
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 方法的一些帮助。
这是我的游乐场链接。
您可以简单地将fmt.Sprintf(...)
与"%020s"
指令一起使用(其中 20 是您想要的总长度(。s
动词将使用大 int 的自然字符串格式,020
修饰符将创建一个总长度(至少(为 20 且零填充(而不是空格(的字符串。
例如(Go Playground(:
m := big.NewInt(99999999999999)
s := fmt.Sprintf("%020s", m)
fmt.Println(s)
// 00000099999999999999
Int.Format()
不是让你手动调用的(尽管你可以(,但它是实现fmt.Formatter
,所以fmt
包将支持格式化big.Int
开箱即用的值。
请参阅此示例:
m := big.NewInt(99)
fmt.Printf("%06dn", m)
if _, ok := m.SetString("1234567890123456789012345678901234567890", 10); !ok {
panic("big")
}
fmt.Printf("%060dn", m)
输出(在Go Playground上尝试(:
000099
000000000000000000001234567890123456789012345678901234567890
这是最简单的,所以使用这个。手动创建fmt.Formatter
可以为您提供更多控制,但也更难做到。除非这是应用的性能关键部分,否则只需使用上述解决方案。