convert variable from string to float in Go
Code snippet on how to convert variable from string to float in Go
package main
import "strconv"
func main() {
str := "50.50"
num, err := strconv.ParseFloat(str, 64)
if err != nil {
panic(err)
}
println(num)
}
This code converts a string variable (str) to a float variable (num). First, the strconv package is imported to use the ParseFloat() function which takes two arguments: the string and the size (in this case 64). Then, using an if statement, the code checks if an error has occurred. If an error did occur, it would trigger a panic. Finally, the float is printed. If there were no errors, the string will be successfully converted into a float value and printed.