strconv.ParseFloat()
functionThe 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
float64
whenbitSize=32
, but it can be converted tofloat32
without altering its value.
func ParseFloat(s string, bitSize int) (float64, error)
s
: This is the string value to parse into the floating-point number.bitSize
: This is to specify the precision. The value of bitSize
can be 32
or 64
.The ParseFloat()
function returns the floating-point number converted from the given string.
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()}
Line 4: We add the main
package.
Lines 6 to 9: We import necessary packages in the Golang project.
Lines 11 to 21: We define the main()
function, variable str
of string type, and assign a value to it. We pass the variable in the ParseFloat()
function, which converts the str
variable to a floating-point number with the precision defined by bitSize
.
Finally, the result is displayed.