How to convert a floating-point number to a string with a specified precision using strconv.FormatFloat() in Golang?

To convert a floating-point number to a string with a specified precision using strconv.FormatFloat() in Golang, you can follow the steps below:

  1. Import the required package: import "strconv"

  2. Declare the floating-point number that you want to convert to a string.

    num := 3.14159
  3. Specify the desired precision using strconv.FormatFloat() function. It takes four arguments: the value to be converted, the format 'f' to specify floating-point format, the precision, and the bit size.

    precision := 2 str := strconv.FormatFloat(num, 'f', precision, 64)

    In this example, we set the precision to 2 and the bit size to 64.

    Note: The bit size argument specifies whether it is a float32 (32 bits) or a float64 (64 bits).

  4. Print the converted value.

    fmt.Println(str)

The complete code snippet looks like this:

package main import ( "fmt" "strconv" ) func main() { num := 3.14159 precision := 2 str := strconv.FormatFloat(num, 'f', precision, 64) fmt.Println(str) }

Output:

3.14

The strconv.FormatFloat() function converts the float to a string representation with the specified precision.