Home >Backend Development >Golang >How to Format Floating Point Numbers in Go: fmt.Sprintf() vs. strconv.FormatFloat()?
In Go, there are several methods to convert a floating point number into a string. Two popular choices include fmt.Sprintf() and strconv.FormatFloat(). Each approach has its nuances, but they ultimately leverage the same underlying string formatting mechanisms.
When deciding between fmt.Sprintf() and strconv.FormatFloat(), consider the following:
Syntax:
func Sprintf(format string, a ...interface{}) string
Usage:
fResult := 123.456 sResult := fmt.Sprintf("%.2f", fResult) // Format the number to two decimal places
Syntax:
func FormatFloat(f float64, fmt byte, prec, bitSize int) string
Usage:
fResult := float64(123.456) sResult := strconv.FormatFloat(fResult, 'f', 2, 32) // Format the number to two decimal places, assuming it's a float64
The bitSize parameter in strconv.FormatFloat() controls how rounding is performed. It assumes that the original floating point value had the specified bit size (32 for float32, 64 for float64). By specifying the correct bitSize, the rounding behavior is optimized for the actual data type of the input.
The above is the detailed content of How to Format Floating Point Numbers in Go: fmt.Sprintf() vs. strconv.FormatFloat()?. For more information, please follow other related articles on the PHP Chinese website!