How to convert a string to a float in Golang

  • 26 June 2020
  • ADM

 

How to convert a string to a float in Golang - images/logos/golang.jpg

 

Here is a simple snippet how to convert a string into a float in Golang. If you need help how to install Golang check the references links.

Code

To convert a string into a float, use the ParseFloat method.

package main

import (
	"fmt"
	"strconv"
)

func main() {

	f, err := strconv.ParseFloat("1.234", 64)
	if err == nil {
		/** displaying the type of the b variable */
		fmt.Printf("Type: %T \n", f)

		/** displaying the string variable into the console */
		fmt.Println("Value:", f)
	}
}

Compile&Run

To compile the code navigate to the file location and run the following command.

$ go build string_to_float.go

Then depending if you are on Linux or Windows the binary file is created.

To run the application execute the command.

Linux

$ string_to_float

Windows

c:\Users\adm\go\tutorials> string_to_float.exe

If you want to compile and run the application in one single step run the following command:

go run string_to_float.go

Output

Will display the f variable type and the corresponding value.

Type: float64
Value: 1.234

 

References