How to Convert Float to String
I Read a Float from a File and Will Have to Convert It to String. My Problem Here Is That I Am Unsure of How Many Digits Will Be There After the Decimal. I...
I read a float from a file and will have to convert it to string. My problem here is that I am unsure of how many digits will be there after the decimal. I need to take the float exactly and convert it to string.
For ex:
1.10 should be converted to "1.10"
Also,
1.5 should be converted to "1.5"
Can someone suggest how to go about this?
4 Answers
Use strconv.FormatFloat like such:
s := strconv.FormatFloat(3.1415, 'f', -1, 64)
fmt.Println(s)
Outputs
3.1415
Must Read
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
func main() {
var x float32
var y string
x= 10.5
y = fmt.Sprint(x)
fmt.Println(y)
}
Depending on the size of your float number choose most suitable option:
var (
floatNumber float64 = 27.156633168032640
)
fmt.Println("as float32 with 'E' (decimal exponent) :", strconv.FormatFloat(floatNumber, 'E', -1, 32))
fmt.Println("as float64 with 'E' (decimal exponent) :", strconv.FormatFloat(floatNumber, 'E', -1, 64))
fmt.Println("as float32 with 'f' (no exponent) :", strconv.FormatFloat(floatNumber, 'f', -1, 32))
fmt.Println("as float64 with 'f' (no exponent) :", strconv.FormatFloat(floatNumber, 'f', -1, 64))
fmt.Println("with fmt.Sprint :", fmt.Sprint(floatNumber))
fmt.Println("with fmt.Sprintf :", fmt.Sprintf("%f", floatNumber))
The result is:
P.S. for better performance you should use strconv.FormatFloat()