【问题标题】:Usage example for Format method with leading zero padding for Big Ints in GolangGolang 中 Big Ints 前导零填充的 Format 方法的使用示例
【发布时间】:2023-04-02 10:42:02
【问题描述】:

我想将大整数格式化为带有前导零的字符串。我正在寻找类似于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

【问题讨论】:

  • 谢谢大家。我只是忘记了 Sprintf。 ://

标签: string go string-formatting


【解决方案1】:

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

例如(Go Playground):

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

【讨论】:

    【解决方案2】:

    Int.Format() 不是供您手动调用的(虽然您可以),但它是为了实现 fmt.Formatter,因此 fmt 包将支持开箱即用地格式化 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 可以让您获得更多控制权,但也更难做到。除非这是您应用的性能关键部分,否则请使用上述解决方案。

    【讨论】:

    • 我想存储字符串,而不是打印它。
    • @Mittenchops 您在问题中没有提到这一点,您提供的示例也会打印到控制台。我在答案中写的所有内容仍然适用,您只需要使用fmt.Sprintf() 而不是fmt.Printf()。更多详情请见Format a Go string without printing?
    猜你喜欢
    • 1970-01-01
    • 2015-05-21
    • 2014-09-19
    • 2011-10-09
    • 2011-03-28
    • 2019-05-26
    • 1970-01-01
    • 2010-11-19
    • 1970-01-01
    相关资源
    最近更新 更多