19

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?
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Nagireddy Hanisha
  • 1,290
  • 4
  • 17
  • 39
  • 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

20

Use strconv.FormatFloat like such:

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

Outputs

3.1415

Ullaakut
  • 3,554
  • 2
  • 19
  • 34
  • Wrong, this outputs `3.1415E+00` (https://go.dev/play/p/-l7YeX1bzAL). use `strconv.FormatFloat(3.1415, 'f', -1, 64)` instead to have `3.1415` (https://go.dev/play/p/sSThokQeavt) – Yanis.F Jul 27 '23 at 04:10
  • Indeed, thanks for the correction @Yanis.F, it is corrected now. – Ullaakut Aug 24 '23 at 11:15
11

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
  • 2,525
  • 1
  • 18
  • 24
7
func main() {
    var x float32
    var y string
    x= 10.5
    y = fmt.Sprint(x)
    fmt.Println(y)
}
pretzelhammer
  • 13,874
  • 15
  • 47
  • 98
Ayush Rastogi
  • 71
  • 1
  • 4
  • 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
1

Depending on the size of your float number choose most suitable option:

var (
    floatNumber float64 = 27.156633168032640
)

fmt.Println("as float32 with 'E' (decimal exponent) :", strconv.FormatFloat(floatNumber, 'E', -1, 32))
fmt.Println("as float64 with 'E' (decimal exponent) :", strconv.FormatFloat(floatNumber, 'E', -1, 64))
fmt.Println("as float32 with 'f' (no exponent) :", strconv.FormatFloat(floatNumber, 'f', -1, 32))
fmt.Println("as float64 with 'f' (no exponent) :", strconv.FormatFloat(floatNumber, 'f', -1, 64))
fmt.Println("with fmt.Sprint :", fmt.Sprint(floatNumber))
fmt.Println("with fmt.Sprintf :", fmt.Sprintf("%f", floatNumber))

The result is:

enter image description here

P.S. for better performance you should use strconv.FormatFloat()

ABDULLOKH MUKHAMMADJONOV
  • 4,249
  • 3
  • 22
  • 40