【问题标题】:How to convert uint64 to string如何将uint64转换为字符串
【发布时间】:2017-06-06 20:34:30
【问题描述】:

我正在尝试使用uint64 打印string,但我使用的strconv 方法的组合都不起作用。

log.Println("The amount is: " + strconv.Itoa((charge.Amount)))

给我:

cannot use charge.Amount (type uint64) as type int in argument to strconv.Itoa

如何打印这个string

【问题讨论】:

    标签: string go type-conversion strconv


    【解决方案1】:

    strconv.Itoa() 需要 int 类型的值,所以你必须给它:

    log.Println("The amount is: " + strconv.Itoa(int(charge.Amount)))
    

    但要知道,如果 int 是 32 位(而 uint64 是 64 位),这可能会丢失精度,符号也不同。 strconv.FormatUint() 会更好,因为它需要 uint64 类型的值:

    log.Println("The amount is: " + strconv.FormatUint(charge.Amount, 10))
    

    更多选项,请看这个答案:Golang: format a string without printing?

    如果您的目的只是打印该值,则无需将其转换为 intstring,请使用以下之一:

    log.Println("The amount is:", charge.Amount)
    log.Printf("The amount is: %d\n", charge.Amount)
    

    【讨论】:

      【解决方案2】:

      如果要将int64 转换为string,可以使用:

      strconv.FormatInt(time.Now().Unix(), 10)
      

      strconv.FormatUint
      

      【讨论】:

        【解决方案3】:

        如果你真的想把它保存在一个字符串中,你可以使用 Sprint 函数之一。例如:

        myString := fmt.Sprintf("%v", charge.Amount)
        

        【讨论】:

        • 为什么不只是fmt.Sprint(charge.Amount)
        【解决方案4】:

        log.Printf

        log.Printf("The amount is: %d\n", charge.Amount)
        

        【讨论】:

          【解决方案5】:

          如果您来这里是为了了解如何将字符串转换为 uint64,那么它是这样完成的:

          newNumber, err := strconv.ParseUint("100", 10, 64)
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2015-08-27
            • 2018-08-31
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-08-09
            • 1970-01-01
            相关资源
            最近更新 更多