简体   繁体   English

如何在Golang中将number(int或float64)转换为字符串

[英]How to convert number (int or float64) to string in Golang

How do I convert any given number which can be a int or float64 to string ? 如何将任何给定的数字(可以是int或float64)转换为字符串?

Using strconv.FormatFloat or FormatInt I have to specify that the given number is a float or integer. 使用strconv.FormatFloat或FormatInt我必须指定给定的数字是浮点数或整数。 In my case it is unknown what I get. 在我的情况下,我不知道我得到了什么。

Behaviour: 行为:

When I get a 5 it should be converted into "5" and not "5.00" 当我得到5它应该被转换成"5"而不是"5.00"

When I get a 1.23 it should be converted into "1.23" and not "1" 当我得到1.23它应该转换为"1.23"而不是"1"

You may use fmt.Sprint 您可以使用fmt.Sprint

fmt.Sprint returns string format of any variable passed to it fmt.Sprint返回传递给它的任何变量的字符串格式

Sample 样品

package main

import (
    "fmt"
)

func main() {
    f := fmt.Sprint(5.03)
    i := fmt.Sprint(5)
    fmt.Println("float:",f,"\nint:",i)
}

play link 播放链接

If you don't know what type the number you need to convert to string will be, you can just use fmt.Sprintf with the %v verb: 如果你不知道你需要转换为字符串的类型是什么类型,你可以使用带有%v动词的fmt.Sprintf

fmt.Sprintf("%v", 1.23) // "1.23"
fmt.Sprintf("%v", 5) // "5"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM