如何将 uint64转换为 string

我试图打印一个 stringuint64,但没有组合的 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

84323 次浏览

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))

有关更多选项,请参见以下答案: 格式化字符串而不打印?

如果您的目的只是打印值,您不需要将其转换为 intstring,请使用以下方法之一:

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

日志,打印文件

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

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

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

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

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

或者

strconv.FormatUint

如果你来这里看如何隐藏字符串 uint64,这是它的做法:

newNumber, err := strconv.ParseUint("100", 10, 64)
func main() {
var a uint64
a = 3
var s string
s = fmt.Sprint(a)
fmt.Printf("%s", s)
}