How to convert float to string

Viewed 22798

I read a float from a file and will have to convert it to string. My problem here is that I am unsure of how many digits will be there after the decimal. I need to take the float exactly and convert it to string.

For ex: 
1.10 should be converted to "1.10"
Also,
1.5 should be converted to "1.5"
Can someone suggest how to go about this?
4 Answers

Use strconv.FormatFloat like such:

s := strconv.FormatFloat(3.1415, 'E', -1, 64)
fmt.Println(s)

Outputs

3.1415

Convert float to string

FormatFloat converts the floating-point number f to a string, according to the format fmt and precision prec. It rounds the result assuming that the original was obtained from a floating-point value of bitSize bits (32 for float32, 64 for float64).

func FormatFloat(f float64, fmt byte, prec, bitSize int) string

f := 3.14159265
s := strconv.FormatFloat(f, 'E', -1, 64)
fmt.Println(s) 

Output is "3.14159265"

Another method is by using fmt.Sprintf

s := fmt.Sprintf("%f", 123.456) 
fmt.Println(s)

Output is "123.456000"

Check the code on play ground

func main() {
    var x float32
    var y string
    x= 10.5
    y = fmt.Sprint(x)
    fmt.Println(y)
}

One line, and that's all :)

str := fmt.Sprint(8.415)
Related