Go Convert String to Float Example with strconv.ParseFloat
In Go, convert a string to a float using
strconv.ParseFloat(string, 64), which returns the float64 value and an error.Examples
Input"3.14"
Output3.14
Input"0.001"
Output0.001
Input"abc"
Outputerror: parsing "abc": invalid syntax
How to Think About It
To convert a string to a float in Go, you use the
strconv.ParseFloat function. It reads the string and tries to turn it into a floating-point number. If the string is not a valid number, it returns an error, so you should always check for that.Algorithm
1
Get the input string that represents a number.2
Call the function to parse the string into a float with 64-bit precision.3
Check if the parsing returned an error.4
If no error, use the float value; otherwise, handle the error.Code
go
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(f) }
Output
3.14
Dry Run
Let's trace converting the string "3.14" to a float.
1
Input string
str = "3.14"
2
Parse string
Call strconv.ParseFloat("3.14", 64)
3
Check error
err is nil, so parsing succeeded
4
Output float
f = 3.14
| Step | Action | Value |
|---|---|---|
| 1 | Input string | "3.14" |
| 2 | Parse string | 3.14, err=nil |
| 3 | Check error | No error |
| 4 | Output float | 3.14 |
Why This Works
Step 1: Use strconv.ParseFloat
The strconv.ParseFloat function reads the string and tries to convert it to a float64 number.
Step 2: Handle errors
If the string is not a valid float, ParseFloat returns an error, so you must check it to avoid crashes.
Step 3: Use the float value
When no error occurs, you can safely use the returned float64 value in your program.
Alternative Approaches
Using fmt.Sscanf
go
package main import ( "fmt" ) func main() { str := "3.14" var f float64 _, err := fmt.Sscanf(str, "%f", &f) if err != nil { fmt.Println("Error:", err) return } fmt.Println(f) }
This method uses formatted scanning but is less common and less flexible than strconv.ParseFloat.
Complexity: O(n) time, O(1) space
Time Complexity
Parsing the string takes time proportional to the length of the string, so it is O(n).
Space Complexity
The function uses a fixed amount of memory regardless of input size, so it is O(1).
Which Approach is Fastest?
Using strconv.ParseFloat is the fastest and most idiomatic way in Go; alternatives like fmt.Sscanf are slower and less straightforward.
| Approach | Time | Space | Best For |
|---|---|---|---|
| strconv.ParseFloat | O(n) | O(1) | Standard, fast, and safe conversion |
| fmt.Sscanf | O(n) | O(1) | Formatted input parsing, less common for simple float conversion |
Always check the error returned by strconv.ParseFloat to handle invalid input safely.
Ignoring the error returned by strconv.ParseFloat can cause your program to crash or behave unexpectedly.