Go strconv.AppendFloat() function is used to “append the string form of the floating-point number”.
Syntax
func AppendFloat(num []byte, val float64, fmt byte, prec, bitSize int) []byte
Parameters
- dst: This is a byte array to which the floating-point number will be appended as a string.
- f: This is the floating-point number to be appended to dst.
- fmt: This is used to specify formatting.
- prec: This is the precision of the floating-point number, which will be appended to the string.
- bitSize: This is the bit size (32 for float32, 64 for float64).
Return value
The strconv.AppendFloat() function returns the extended buffer after appending the given floating-point value.
Example 1: How to Use strconv.AppendFloat() function
package main
import (
"fmt"
"strconv"
)
func main() {
b := []byte("float: ")
b = strconv.AppendFloat(b, 123.456, 'f', 2, 64)
fmt.Println(string(b))
}
Output
float: 123.46
Example 2: Generates a CSV of float numbers using strconv.AppendFloat()
We will generate a string that represents a CSV (Comma Separated Values) of float numbers using strconv.AppendFloat(), and then writes the CSV string to a file.
package main
import (
"log"
"os"
"strconv"
)
func main() {
data := [][]float64{
{1.23, 4.56, 7.89},
{9.87, 6.54, 3.21},
{2.34, 5.67, 8.90},
}
// Convert float64 slices to CSV format and write to file
err := WriteFloatsToCSV("data.csv", data)
if err != nil {
log.Fatalf("Error writing to CSV: %v", err)
}
}
// WriteFloatsToCSV writes float64 slices to a CSV file
func WriteFloatsToCSV(filename string, data [][]float64) error {
f, err := os.Create(filename)
if err != nil {
return err
}
defer f.Close()
for _, row := range data {
s := make([]byte, 0, 64)
for i, number := range row {
if i != 0 {
s = append(s, ',')
}
s = strconv.AppendFloat(s, number, 'f', 2, 64)
}
s = append(s, '\n')
_, err := f.Write(s)
if err != nil {
return err
}
}
return nil
}
Output
It will create a data.csv file that looks like this:
That’s it.

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.