To convert a string to a floating-point number in Golang, you can use the strconv.ParseFloat()
function. Here's an example of how you can use it:
package main
import (
"fmt"
"strconv"
)
func main() {
str := "3.14"
f, err := strconv.ParseFloat(str, 64)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Float:", f)
}
In this example, the str
variable holds the string you want to convert to a floating-point number. The strconv.ParseFloat()
function is used to convert the string to a floating-point number, with the second argument being the bit size (64 in this case) that determines the precision of the floating-point number.
The function returns two values - the converted floating-point number and an error. If the conversion is successful, f
will hold the float value, and err
will be nil
. Otherwise, if there is an error during the conversion, err
will contain the error details, and f
will be 0
.
In the example, the converted floating-point number is printed using fmt.Println()
.