How to convert a float to string in Golang

  • 11 June 2020
  • ADM

 

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

 

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

Code

FormatFloat converts the floating-point number f to a string, according to the format fmt and precision prec. It rounds the result assuming that the original was obtained from a floating-point value of bitSize bits (32 for float32, 64 for float64).

package main

import (
	"fmt"
	"strconv"
)

func main() {
	/** float variable */
	f := 1.23456789

	/** converting the f variable into a string */
	/** 5 is the number of decimals */
	/** 64 is for float64 type*/
	str := strconv.FormatFloat(f, 'f', 5, 64)

	/** displaying the string variable into the console */
	fmt.Println(str)
}

Compile&Run

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

$ go build float_to_string.go

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

To run the application execute the command.

Linux

$ float_to_string

Windows

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

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

go run float_to_string.go

Output

Will display the float number in string format with 5 decimal points.

1.23457

 

References