Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

golang
go
communitycreator

How can we convert a float into a string in Golang

Shubham Singh Kshatriya

A float can be converted into a string, in Golang, using the following two functions:

  • FormatFloat: This function is available within the strconv package.

  • Sprintf: This function is available within the fmt package.

FormatFloat

The FormatFloat function converts the floating-point number into a string, according to the format and precision. It also rounds off the result.

The code snippet below shows us how to convert a float into a string while using the FormatFloat function.

package main
  
import (
    "fmt"
    "strconv"
)

func main() {
    // float
    f := 3.14159 
    // convert to string
    s := strconv.FormatFloat(f, 'g', 5, 64)
    
    fmt.Printf("Type of s: %T\n", s)
    fmt.Printf("Type of f: %T\n", f)
    fmt.Println()
    fmt.Printf("Value of s: %v\n", s)
    fmt.Printf("Value of f: %v", f)
}
Float to String using FormatFloat

Sprintf

The code snippet below shows us how to convert a float into a string, while using the Sprintf function.

package main
  
import (
    "fmt"
)

func main() {
    // float
    f := 3.14159 
    // convert to string
    s := fmt.Sprintf("%v", f)
    
    fmt.Printf("Type of s: %T\n", s)
    fmt.Printf("Type of f: %T\n", f)
    fmt.Println()
    fmt.Printf("Value of s: %v\n", s)
    fmt.Printf("Value of f: %v", f)
}
Converting a float into a string, using "Sprintf"

RELATED TAGS

golang
go
communitycreator

CONTRIBUTOR

Shubham Singh Kshatriya
RELATED COURSES

View all Courses

Keep Exploring