在Golang中将uint64转换为字符串

在Golang中将uint64转换为字符串

问题描述:

我正试图打印 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这个呢?

我正在尝试使用 uint64 code>打印 string code> 但我使用的 strconv code>方法没有任何组合有效。 p>

  log.Println(“数量为:” + strconv.Itoa((charge  .Amount))))
  code>  pre> 
 
 

给我: p>

不能使用charge.Amount(类型uint64)作为类型 int in strconv.Itoa code> p>

如何打印此 string code>? p> div>

strconv.Itoa() expects a value of type int, so you have to give it that:

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

But know that this may lose precision if int is 32-bit (while uint64 is 64), also sign-ness is different. strconv.FormatUint() would be better as that expects a value of type uint64:

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

For more options, see this answer: Golang: format a string without printing?

If your purpose is to just print the value, you don't need to convert it, neither to int nor to string, use one of these:

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

log.Printf

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

If you actually want to keep it in a string you can use one of Sprint functions. For instance:

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

if you want to convert int64 to string, you can use :

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

or

strconv.FormatUint

If you came here looking on how to covert string to uint64, this is how its done:

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