golang

Golang String to Float

It is common for programmers to convert values from one type to another. One such conversion type is converting a string to a floating-point value. For example, you can use input from the user to convert it to a float and perform the desired operations.

This post will cover how to convert a string to a floating-point number in the Go programming language.

Importing Packages

To convert a string to a float in go, we will need to import the strconv package. You can do this by adding the following import block:

import "strconv"

The strconv or String Conversion package provides with a collection of methods to convert strings to and from other types.

String to Float – ParseFloat()

The strconv package provides a ParseFloat() method that allows you to parse a string to a floating-point value with a specified precision by the bitSize parameter.

The function syntax is as shown:

func ParseFloat(s string, bitSize int) (float64, error)

The function takes in the string to parse and the bitSize as the parameters. The bitSize determines the precision. Accepted values for the bitSize parameter are 32 for float32 and 64 for float64.

HINT: if you set the bitSize to 32, the result is still of float64 but can be converted to float32 while retaining its value.

The following example shows how to use the ParseInt() method to convert a string to a float.

packagemain
import (
    "fmt"
    "reflect"
    "strconv"
)
funcmain() {
    str := "3.4028237"
    m_float, _ := strconv.ParseFloat(str, 64)
    fmt.Println(reflect.TypeOf(m_float), "=> ", str)
}

The above example takes the string and parses it to a 64-bit float value. The resulting output is as:

float64 => 3.4028237

To convert to a 32-bit floating-point, you can change the bitSize as:

m_float, _ := strconv.ParseFloat(str, 32)

Float to String – Sprintf()

We can format a float to a string using the %f formatter in the Sprintf() method from the fmt package.

Consider the example below:

packagemain
import (
    "fmt"
    "reflect"
)
funcmain() {
    m_float:= 3.14159265
    to_str := fmt.Sprintf("%f", m_float)

    fmt.Println(reflect.TypeOf(to_str), "=> ", to_str)
}

The Sprintf method will convert the float to a string type, as shown in the output below:

string => 3.141593

Conclusion

This guide takes you on a brief tour of how to convert a string to a floating-point type and vice versa.

Stay tuned for more.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list