How to Use the strconv.AppendFloat() Function in Golang

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

  1. dst: This is a byte array to which the floating-point number will be appended as a string.
  2. f: This is the floating-point number to be appended to dst.
  3. fmt: This is used to specify formatting.
  4. prec: This is the precision of the floating-point number, which will be appended to the string.
  5. 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:

data.csv

That’s it.

Leave a Comment