How to convert uint64 to string

StringGoType ConversionStrconv

String Problem Overview


I am trying to print a string with a uint64 but no combination of strconv methods that I use is working.

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

Gives me:

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

How can I print this string?

String Solutions


Solution 1 - String

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: https://stackoverflow.com/questions/11123865/golang-format-a-string-without-printing/31742265#31742265

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\n", charge.Amount)

Solution 2 - String

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

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

or

strconv.FormatUint

Solution 3 - String

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)

Solution 4 - String

log.Printf

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

Solution 5 - String

func main() {
	var a uint64
	a = 3
	var s string
	s = fmt.Sprint(a)
	fmt.Printf("%s", s)
}

Solution 6 - String

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnthonyView Question on Stackoverflow
Solution 1 - StringiczaView Answer on Stackoverflow
Solution 2 - Stringlingwei64View Answer on Stackoverflow
Solution 3 - StringPeter FendrichView Answer on Stackoverflow
Solution 4 - StringctcherryView Answer on Stackoverflow
Solution 5 - StringYongqi ZView Answer on Stackoverflow
Solution 6 - StringBill ZelenkoView Answer on Stackoverflow