How to Convert Float to String type in Go?
Like most modern languages, Golang includes Float as a built-in type. Let's take an example, you may have a variable that contains a Float value. In order to convert Float value into string type in Golang, you can use the following methods.
FormatFloat method
You can use the strconv package's FormatFloat() function to convert the float into an string value. 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).
Syntax
func FormatFloat(f float64, fmt byte, prec, bitSize int) string
Example
package main
import (
"fmt"
"reflect"
"strconv"
)
func main() {
var f float64 = 3.1415926535
fmt.Println(reflect.TypeOf(f))
fmt.Println(f)
var s string = strconv.FormatFloat(f, 'E', -1, 32)
fmt.Println(reflect.TypeOf(s))
fmt.Println(s)
}
Output
float64
3.1415926535
string
3.1415927E+00
fmt.Sprintf() method
Sprintf formats according to a format specifier and returns the resulting string. Here, a is of Interface type hence you can use this method to convert any type to string.
Syntax
func Sprintf(format string, a ...interface{}) string
Example
package main
import (
"fmt"
"reflect"
)
func main() {
b := 12.454
fmt.Println(reflect.TypeOf(b))
s := fmt.Sprintf("%v", b)
fmt.Println(s)
fmt.Println(reflect.TypeOf(s))
}
Output
float64
12.454
string
Most Helpful This Week
Golang program for implementation of Comb Sort
Golang program to generate number of slices permutations of number entered by user
How to add items to Slice using append function in Golang?
Pascal triangle in Go Programming Language
How to read current directory using Readdir?
How to change slice item value in Golang?
Cannot call non-function <variable> error in Golang
How to Improve the Performance of Your Golang Application?
Go program to find Name Server (NS) record of a domain
How To Make an HTTP Server in Golang?
Most Helpful This Week
Split a character string based on change of characterGenerate a Keygen of 256 bitsGet Set and Clear Session in GolangRegular expression to extract date(YYYY-MM-DD) from stringGolang Get current Date and Time in EST, UTC and MST?Sample program to create csv and write dataExample to use Weekday and YearDay functionHow to read names of all files and folders in current directory?URL parser in GolangHow to read current directory using Readdir?