9

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?
Flimzy
  • 68,325
  • 15
  • 126
  • 165
Nagireddy Hanisha
  • 1,090
  • 3
  • 16
  • 33
  • 2
    Possible duplicate of [How to format floating point numbers into a string using Go](https://stackoverflow.com/questions/18951359/how-to-format-floating-point-numbers-into-a-string-using-go) – nilsocket Nov 15 '18 at 06:05

4 Answers4

11

Use strconv.FormatFloat like such:

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

Outputs

3.1415

Ullaakut
  • 3,223
  • 1
  • 15
  • 29
8

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

ASHWIN RAJEEV
  • 1,921
  • 1
  • 16
  • 22
7
func main() {
    var x float32
    var y string
    x= 10.5
    y = fmt.Sprint(x)
    fmt.Println(y)
}
pretzelhammer
  • 12,263
  • 15
  • 41
  • 88
Ayush Rastogi
  • 71
  • 1
  • 2
  • Be careful when using `fmt.Sprint` and other similar functions, as they are slower and make more allocations than using `strconv` functions. – Ullaakut Dec 14 '21 at 07:33
3

One line, and that's all :)

str := fmt.Sprint(8.415)
Amin Shojaei
  • 3,796
  • 2
  • 27
  • 38