How to convert a string to a float in Golang

A string can be converted to a float in Golang using the ParseFloat function within the strconv package.

The strconv package provides methods to implement conversions to and from string representations.

Syntax

floatNum, error := strconv.ParseFloat(stringNum, bitSize)

Parameters

The strconv.ParseFloat() function accepts the following parameters.

  • stringNum: The string number that needs to be converted to float.
  • bitSize: The precision of the float number specified in the int type (32 for float32 and 64 for float64).

Return value

If the input string is numeric, then this function will return a float64 value.

If the input string is non-numeric, then this function will throw an invalid syntax error and the float value will be set to 0.

Example

The code snippet below shows how to convert a string to a float using the ParseFloat function.

package main
import (
"fmt"
"strconv"
)
func main() {
// Using numeric value
fmt.Println("Using numeric value")
str1 := "3.14159"
float1, error1 := strconv.ParseFloat(str1, 64)
if error1 != nil {
fmt.Println(error1)
} else {
fmt.Printf("Type of str1: %T\n", str1)
fmt.Printf("Type of float1: %T\n", float1)
fmt.Printf("Value of str1: %v\n", str1)
fmt.Printf("Value of float1: %v\n", float1)
}
fmt.Println()
// using non-numeric value
fmt.Println("Using non-numeric value")
str2 := "eDprEsSo"
float2, error2 := strconv.ParseFloat(str2, 64)
if error2 != nil {
fmt.Println(error2)
} else {
fmt.Printf("Type of str2: %T\n", str2)
fmt.Printf("Type of float2: %T\n", float2)
fmt.Printf("Value of str2: %v\n", str2)
fmt.Printf("Value of float2: %v", float2)
}
}

Explanation

We declared a numeric string str1 (line 11) and converted it to float using the strconv.ParseFloat() method (line 12). In this case, there shouldn’t be any error, and the else block will be executed (line 15) where we display the type and value of str1 and float1 respectively on the console.

Again, we declare a string str2 (line 26) but this time it’s non-numeric. We again convert it to float (line 27) but since the value is non-numeric, it will return an error, and the if block will be executed (line 28) where we display the error on the console.

Free Resources