How can we convert a float into a string in Golang

A float can be converted into a string, in Golang, using the following two functions:

  • FormatFloat: This function is available within the strconv package.

  • Sprintf: This function is available within the fmt package.

FormatFloat

The FormatFloat function converts the floating-point number into a string, according to the format and precision. It also rounds off the result.

The code snippet below shows us how to convert a float into a string while using the FormatFloat function.

package main
import (
"fmt"
"strconv"
)
func main() {
// float
f := 3.14159
// convert to string
s := strconv.FormatFloat(f, 'g', 5, 64)
fmt.Printf("Type of s: %T\n", s)
fmt.Printf("Type of f: %T\n", f)
fmt.Println()
fmt.Printf("Value of s: %v\n", s)
fmt.Printf("Value of f: %v", f)
}

Sprintf

The code snippet below shows us how to convert a float into a string, while using the Sprintf function.

package main
import (
"fmt"
)
func main() {
// float
f := 3.14159
// convert to string
s := fmt.Sprintf("%v", f)
fmt.Printf("Type of s: %T\n", s)
fmt.Printf("Type of f: %T\n", f)
fmt.Println()
fmt.Printf("Value of s: %v\n", s)
fmt.Printf("Value of f: %v", f)
}

Free Resources