Use strconv.FormatFloat like such:
s := strconv.FormatFloat(3.1415, 'f', -1, 64)
fmt.Println(s)
Outputs
Answer from Ullaakut on Stack Overflow
3.1415
Use strconv.FormatFloat like such:
s := strconv.FormatFloat(3.1415, 'f', -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
Converting a float to string
Problem converting float32 to string
go - formatFloat : convert float number to string - Stack Overflow
Issue with type conversion from float64 to string
What is the easy way of converting a float to a string?
The strconv package seems awfully cluttered and there doesn't seem to be a function where you can simply give a float and get a string
Both fmt.Sprintf and strconv.FormatFloat use the same string formatting routine under the covers, so should give the same results.
If the precision that the number should be formatted to is variable, then it is probably easier to use FormatFloat, since it avoids the need to construct a format string as you would with Sprintf. If it never changes, then you could use either.
The last argument to FormatFloat controls how values are rounded. From the documentation:
It rounds the result assuming that the original was obtained from a floating-point value of bitSize bits (32 for float32, 64 for float64)
So if you are working with float32 values as in your sample code, then passing 32 is correct.
You will have with Go 1.12 (February 2019) and the project cespare/ryu a faster alternative to strconv:
Ryu is a Go implementation of Ryu, a fast algorithm for converting floating-point numbers to strings.
It is a fairly direct Go translation of Ulf Adams's C library.
The
strconv.FormatFloatlatency is bimodal because of an infrequently-taken slow path that is orders of magnitude more expensive (issue 15672).The Ryu algorithm requires several lookup tables.
Ulf Adams's C library implements a size optimization (RYU_OPTIMIZE_SIZE) which greatly reduces the size of thefloat64tables in exchange for a little more CPU cost.For a small fraction of inputs, Ryu gives a different value than
strconvdoes for the last digit.
This is due to a bug instrconv: issue 29491.
Go 1.12 might or might not include that new implementation directly in strconv, but if it does not, you can use this project for faster conversion.