Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?
like image 662
Nagireddy Hanisha Avatar asked Nov 15 '18 05:11

Nagireddy Hanisha


4 Answers

Use strconv.FormatFloat like such:

s := strconv.FormatFloat(3.1415, 'E', -1, 64)
fmt.Println(s)

Outputs

3.1415

like image 120
Ullaakut Avatar answered Oct 24 '22 03:10

Ullaakut


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

like image 35
ASHWIN RAJEEV Avatar answered Oct 24 '22 03:10

ASHWIN RAJEEV


func main() {
    var x float32
    var y string
    x= 10.5
    y = fmt.Sprint(x)
    fmt.Println(y)
}
like image 7
Ayush Rastogi Avatar answered Oct 24 '22 02:10

Ayush Rastogi


One line, and that's all :)

str := fmt.Sprint(8.415)
like image 3
Amin Shojaei Avatar answered Oct 24 '22 01:10

Amin Shojaei