How to Convert String to Float in Go

Use the `strconv.ParseFloat` function from the standard library to convert a string to a float, specifying the bit size (32 or 64) and handling the returned error.

Use the strconv.ParseFloat function from the standard library to convert a string to a float, specifying the bit size (32 or 64) and handling the returned error. If the string is invalid, the function returns an error rather than panicking, so you must check the error value before using the result.

Here is the standard approach for parsing a string into a float64:

package main

import (
	"fmt"
	"strconv"
)

func main() {
	input := "3.14159"
	
	// Parse to float64 (bitSize 64)
	val, err := strconv.ParseFloat(input, 64)
	if err != nil {
		fmt.Println("Invalid float:", err)
		return
	}

	fmt.Printf("Converted value: %f\n", val)
}

If you specifically need a float32, pass 32 as the bit size and cast the result:

input := "12.5"
val64, err := strconv.ParseFloat(input, 32)
if err != nil {
	// handle error
	return
}
val32 := float32(val64)

Common pitfalls include passing non-numeric strings (like "abc" or "12.3.4"), which will trigger an error, or omitting the error check entirely. Unlike some other languages, Go does not silently fail or return zero on invalid input; it forces you to handle the failure case explicitly. This makes your code more robust but requires the if err != nil pattern every time you perform a conversion.

For command-line tools or quick scripts where you might want to ignore errors (not recommended for production), you can use the blank identifier, but be aware this hides potential bugs:

val, _ := strconv.ParseFloat("10.5", 64)

Always prefer checking the error in production code to ensure data integrity.