How to format floating point numbers into a string using Go

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.FormatFloat latency 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 the float64 tables in exchange for a little more CPU cost.

For a small fraction of inputs, Ryu gives a different value than strconv does for the last digit.
This is due to a bug in strconv: 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.

Tags:

Go