string 如何将 uint64 转换为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41787620/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert uint64 to string
提问by Anthony
I am trying to print a string
with a uint64
but no combination of strconv
methods that I use is working.
我想打印string
一个uint64
,但没有结合strconv
的方法,我使用的是工作。
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
cannot use charge.Amount (type uint64) as type int in argument to strconv.Itoa
How can I print this string
?
我怎样才能打印这个string
?
回答by icza
strconv.Itoa()
expects a value of type int
, so you have to give it that:
strconv.Itoa()
需要一个 type 值int
,所以你必须给它:
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
:
但是要知道,如果int
是 32 位(而uint64
64位),这可能会失去精度,而且符号也不同。strconv.FormatUint()
会更好,因为它需要一个类型的值uint64
:
log.Println("The amount is: " + strconv.FormatUint(charge.Amount, 10))
For more options, see this answer: Golang: format a string without printing?
有关更多选项,请参阅此答案:Golang:格式化字符串而不打印?
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:
如果您的目的只是打印值,则无需将其转换为 toint
或 to string
,请使用以下方法之一:
log.Println("The amount is:", charge.Amount)
log.Printf("The amount is: %d\n", charge.Amount)
回答by lingwei64
if you want to convert int64
to string
, you can use :
如果要转换int64
为string
,可以使用:
strconv.FormatInt(time.Now().Unix(), 10)
or
或者
strconv.FormatUint
回答by Peter Fendrich
If you actually want to keep it in a string you can use one of Sprint functions. For instance:
如果你真的想把它保存在一个字符串中,你可以使用 Sprint 函数之一。例如:
myString := fmt.Sprintf("%v", charge.Amount)
回答by ctcherry
回答by Bill Zelenko
If you came here looking on how to covert string to uint64, this is how its done:
如果您来这里是想了解如何将字符串转换为 uint64,那么它就是这样做的:
newNumber, err := strconv.ParseUint("100", 10, 64)