How to use the strconv.ParseFloat() function in Golang
Golang strconv.ParseFloat() function
The ParseFloat() function is a strconv package inbuilt function that converts strings to a floating-point number with the precision defined by the bitSize. The value of bitSize must be 32 or 64. 32 is used for float32, and 64 is used for float64.
Note: The converted result has type
float64whenbitSize=32, but it can be converted tofloat32without altering its value.
Syntax
func ParseFloat(s string, bitSize int) (float64, error)
Parameter
s: This is the string value to parse into the floating-point number.bitSize: This is to specify the precision. The value ofbitSizecan be32or64.
Return value
The ParseFloat() function returns the floating-point number converted from the given string.
Code
The following code shows how to implement the strconv.ParseFloat() function in Golang:
// Golang program// strconv.ParseFloat() Functionpackage mainimport ("fmt""strconv")func main() {// delare variable of type stringvar str string// assigning valuestr = "40.98"// ParseFloat() converts variable str to a floating-point number// with the precision defined by bitSize// diplays resultfmt.Println(strconv.ParseFloat(str, 32))fmt.Println(strconv.ParseFloat(str, 64))fmt.Println()// reassigning valuestr = "-104.23101"// ParseFloat() converts variable str to a floating-point number// with the precision defined by bitSize// diplays resultfmt.Println(strconv.ParseFloat(str, 32))fmt.Println(strconv.ParseFloat(str, 64))fmt.Println()}
Explanation
-
Line 4: We add the
mainpackage. -
Lines 6 to 9: We import necessary packages in the Golang project.
-
Lines 11 to 21: We define the
main()function, variablestrof string type, and assign a value to it. We pass the variable in theParseFloat()function, which converts thestrvariable to a floating-point number with the precision defined bybitSize. -
Finally, the result is displayed.