Convert String to Float

To convert a String to a Float value in Go programming, use ParseFloat() function of strconv package.

In this tutorial, we will learn the syntax of ParseFloat() function, and how to use this function to parse or convert a string to float value.

Syntax

The syntax of ParseFloat() function is

</>
Copy
ParseFloat(str string, bitSize int)

where str is string value, and bitSize the 32 or 64 which specifies the resulting size of float value in bits.

Return Value

The function returns (float, error).

Examples

Float Bit Size of 32

In the following program, we take a string str. We convert this string value to float value with bit size of 32.

example.go

</>
Copy
package main

import (
	"fmt"
	"strconv"
)

func main() {
	var str = "14.2356"
	result, err := strconv.ParseFloat(str, 32)

	if err == nil {
		fmt.Println("The float value is :", result)
	} else {
		fmt.Println("There is an error converting string to float.")
	}
}

Output

The float value is : 14.235600471496582

Float Bit Size of 64

In the following program, we take a string str. We convert this string value to float value with bit size of 32.

example.go

</>
Copy
package main

import (
	"fmt"
	"strconv"
)

func main() {
	var str = "14.2356"
	result, err := strconv.ParseFloat(str, 64)

	if err == nil {
		fmt.Println("The float value is :", result)
	} else {
		fmt.Println("There is an error converting string to float.")
	}
}

Output

The float value is : 14.2356

Negative Scenario

In the following program, we will take a string that has some non-numeric characters. We will try converting it to a float value. We should get an error.

example.go

</>
Copy
package main

import (
	"fmt"
	"strconv"
)

func main() {
	var str = "14.hello356"
	result, err := strconv.ParseFloat(str, 64)

	if err == nil {
		fmt.Println("The float value is :", result)
	} else {

		fmt.Println("There is an error converting string to float.")
		fmt.Println(err)
	}
}

Output

There is an error converting string to float.
strconv.ParseFloat: parsing "14.hello356": invalid syntax

We received a “invalid syntax” error while trying to parse a string that contains characters not allowed in a float value.

Conclusion

In this Golang Tutorial, we learned how to convert a String to Float value in Go language, with example programs.