String Golang中带前导零填充的大整数格式方法的使用示例

String Golang中带前导零填充的大整数格式方法的使用示例,string,go,string-formatting,String,Go,String Formatting,我想将大整数格式化为带前导零的字符串。我想找一个类似的例子,但有点大: 我在看来源 但当我打电话时: 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 "%01000000000

我想将大整数格式化为带前导零的字符串。我想找一个类似的例子,但有点大:

我在看来源

但当我打电话时:

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(),但零填充似乎会使这一点复杂化,因此我特别希望获得有关格式化方法的帮助。)

以下是。

不允许您手动调用(尽管您可以),但它是要实现的,因此包将支持开箱即用的格式化值

请参见此示例:

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

if _, ok := m.SetString("1234567890123456789012345678901234567890", 10); !ok {
    panic("big")
}
fmt.Printf("%060d\n", m)
输出(在屏幕上试用):

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

您只需使用
%020s”
指令即可(其中20是您想要的总长度)。
s
动词将使用大整数的自然字符串格式,
020
修饰符将创建一个总长度(至少)为20且填充为零(而不是空白)的字符串

例如():


我想存储字符串,而不是打印它。@Mittenchops您在问题中没有提到这一点,您提供的示例也会打印到控制台。我在答案中写的所有内容仍然适用,您只需使用
fmt.Sprintf()
而不是
fmt.Printf()
。有关更多详细信息,请参见“谢谢大家”。我只是忘记了斯普林特/
000099
000000000000000000001234567890123456789012345678901234567890
m := big.NewInt(99999999999999)
s := fmt.Sprintf("%020s", m)
fmt.Println(s)
// 00000099999999999999