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
Exploring Blockchain: Top 15 Real-World Use Cases in 2024
Golang program for implementation of Median of Medians
GO supports the standard arithmetic operators: (Addition, Subtraction, Multiplication, Division,Remainder)
Golang program for implementation of Shell Sort
How to check if an item exists in Slice in Golang?
Golang panic recover example
Most Helpful This Week
Regular expression to extract DNS host-name or IP Address from stringHow pointer & and * and ** works in Golang?Passing multiple string arguments to a variadic functionHow to fetch an Integer variable as String in Go?How to fix race condition using Atomic Functions in Golang?How to use Ellipsis (...) in Golang?Example: Arrays of Arrays, Arrays of Slices, Slices of Arrays and Slices of SlicesHow to split a string on white-space?Example: How to use ReadAtLeast from IO Package in Golang?Example to create custom error