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 mainimport ("fmt""strconv")func main() {// floatf := 3.14159// convert to strings := 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 mainimport ("fmt")func main() {// floatf := 3.14159// convert to strings := 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)}