Use strconv.FormatFloat like such:
s := strconv.FormatFloat(3.1415, 'f', -1, 64)
fmt.Println(s)
Outputs
Answer from Ullaakut on Stack Overflow
3.1415
Use strconv.FormatFloat like such:
s := strconv.FormatFloat(3.1415, 'f', -1, 64)
fmt.Println(s)
Outputs
3.1415
Convert float to string
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).
func FormatFloat(f float64, fmt byte, prec, bitSize int) string
f := 3.14159265
s := strconv.FormatFloat(f, 'E', -1, 64)
fmt.Println(s)
Output is "3.14159265"
Another method is by using fmt.Sprintf
s := fmt.Sprintf("%f", 123.456)
fmt.Println(s)
Output is "123.456000"
Check the code on play ground
Problem converting float32 to string
Converting a float to string
go - formatFloat : convert float number to string - Stack Overflow
go - Converting string input to float64 using ParseFloat in Golang - Stack Overflow
What is the easy way of converting a float to a string?
The strconv package seems awfully cluttered and there doesn't seem to be a function where you can simply give a float and get a string
The problem is that you try to parse "x.x\n", e.g: 1.8\n. And this returns an error: strconv.ParseFloat: parsing "1.8\n": invalid syntax. You can do a strings.TrimSpace function or to convert feet[:len(feet)-1] to delete \n character
With strings.TrimSpace() (you need to import strings package):
feetFloat, _ := strconv.ParseFloat(strings.TrimSpace(feet), 64)
Wtih feet[:len(feet)-1]:
feetFloat, _ := strconv.ParseFloat(feet[:len(feet)-1], 64)
Output in both cases:
10.8 feet converted to meters give you 3.2918400000000005 meters
just tested this solution and also added one more feature:
func lbsToGrams(lbs float64) (grams float64) {
return lbs * conversionWeight
}
Find out more on my github here
You may use fmt.Sprint
fmt.Sprint returns string format of any variable passed to it
Sample
package main
import (
"fmt"
)
func main() {
f := fmt.Sprint(5.03)
i := fmt.Sprint(5)
fmt.Println("float:",f,"\nint:",i)
}
play link
If you don't know what type the number you need to convert to string will be, you can just use fmt.Sprintf with the %v verb:
fmt.Sprintf("%v", 1.23) // "1.23"
fmt.Sprintf("%v", 5) // "5"