简体   繁体   中英

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 ?

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"

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,"\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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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