How to convert a float to a string in Golang

Last updated on Aug 7, 2022 by Suraj Sharma



In this tutorial, you will learn how you can convert a float value to a string value in golang


We will use the Sprintf function from the go fmt module to convert a float to a string.


Example


package main

import "fmt"

func main() {
    var a float64
    
    a = 2.456786

    var str string

    str = fmt.Sprintf("%v", a)

    fmt.Printf("string value of a float64 is %s \n", str)
}


Round float to 2 decimal places


We will use the above Sprintf function to round the value of float type to 2 decimal places and convert it to a string.


Example


package main

import "fmt"

func main() {
    var a float64
    
    a = 2.456786

    var str string

    str = fmt.Sprintf("%.2f", a)

    fmt.Printf("Round to 2 decimal places: %s \n", str)
}


Related Solutions


Rate this post


Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.