This post will cover how to convert a string to a floating-point number in the Go programming language.
Importing Packages
To convert a string to a float in go, we will need to import the strconv package. You can do this by adding the following import block:
The strconv or String Conversion package provides with a collection of methods to convert strings to and from other types.
String to Float – ParseFloat()
The strconv package provides a ParseFloat() method that allows you to parse a string to a floating-point value with a specified precision by the bitSize parameter.
The function syntax is as shown:
The function takes in the string to parse and the bitSize as the parameters. The bitSize determines the precision. Accepted values for the bitSize parameter are 32 for float32 and 64 for float64.
HINT: if you set the bitSize to 32, the result is still of float64 but can be converted to float32 while retaining its value.
The following example shows how to use the ParseInt() method to convert a string to a float.
import (
"fmt"
"reflect"
"strconv"
)
funcmain() {
str := "3.4028237"
m_float, _ := strconv.ParseFloat(str, 64)
fmt.Println(reflect.TypeOf(m_float), "=> ", str)
}
The above example takes the string and parses it to a 64-bit float value. The resulting output is as:
To convert to a 32-bit floating-point, you can change the bitSize as:
Float to String – Sprintf()
We can format a float to a string using the %f formatter in the Sprintf() method from the fmt package.
Consider the example below:
import (
"fmt"
"reflect"
)
funcmain() {
m_float:= 3.14159265
to_str := fmt.Sprintf("%f", m_float)
fmt.Println(reflect.TypeOf(to_str), "=> ", to_str)
}
The Sprintf method will convert the float to a string type, as shown in the output below:
Conclusion
This guide takes you on a brief tour of how to convert a string to a floating-point type and vice versa.
Stay tuned for more.