douhuan4699 2017-06-14 08:45 采纳率: 100%
浏览 6013
已采纳

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

How do I convert any given number which can be a int or float64 to string ?

Using strconv.FormatFloat or FormatInt I have to specify that the given number is a float or integer. 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"

When I get a 1.23 it should be converted into "1.23" and not "1"

  • 写回答

3条回答 默认 最新

  • drxd54816 2017-06-14 08:56
    关注

    You may use fmt.Sprint

    fmt.Sprint returns string format of any variable passed to it

    Sample

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        f := fmt.Sprint(5.03)
        i := fmt.Sprint(5)
        fmt.Println("float:",f,"
    int:",i)
    }
    

    play link

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?