Menu Close

Go – How to append float value to slice of bytes in go

strconv.AppendFloat() function is used to append float value to the slice of bytes in go. It appends float value in multiple format.

AppendFloat() function of strconv package is used to appends the string form of the floating-point number f, as generated by FormatFloat, to dst.

Function prototype:

func AppendFloat(dst []byte, f float64, fmt byte, prec, bitSize int) []byte

Input parameters:
dst: Destination where float value to be appended
f: It contains either float32 or float64 value to be appended to dst
fmt: Format of float value
prec: Precision in float value
bitSize: Either 32 or 64. It means either float32 or float64

Returns:
1: It returns the extended buffer i.e slice of bytes having appended float value.

Explanation on how to append float value to slice of bytes in go

  • AppendFloat() function appends float value at the end of destination.

Example:

1)
b32 := []byte("float32: ")
b32 = strconv.AppendFloat(b32, 3.1415926535, 'f', -1, 32)

Output:
float32: 3.1415927

2)
b32 = []byte("float32: ")
b32 = strconv.AppendFloat(b32, 3.1415926535, 'E', -1, 32)

Output:
float32: 3.1415927E+00

3)
b64 := []byte("float64: ")
b64 = strconv.AppendFloat(b64, 3.1415926535, 'f', -1, 64)

Output:
float64: 3.1415926535

Example with code:

package main

import (
	"fmt"
	"strconv"
)

func main() {
    b32 := []byte("float32: ")
	b32 = strconv.AppendFloat(b32, 3.1415926535, 'f', -1, 32)
	fmt.Println(string(b32))
	
	b32 = []byte("float32: ")
	b32 = strconv.AppendFloat(b32, 3.1415926535, 'E', -1, 32)
	fmt.Println(string(b32))
	
	b32 = []byte("float32: ")
	b32 = strconv.AppendFloat(b32, 3.1415926535, 'b', 6, 32)
	fmt.Println(string(b32))
	
	
	b64 := []byte("float64: ")
	b64 = strconv.AppendFloat(b64, 3.1415926535, 'f', -1, 64)
	fmt.Println(string(b64))
	
	b64 = []byte("float64: ")
	b64 = strconv.AppendFloat(b64, 3.1415926535, 'E', -1, 64)
	fmt.Println(string(b64))
	
	b64 = []byte("float64: ")
	b64 = strconv.AppendFloat(b64, 3.1415926535, 'f', 4, 64)
	fmt.Println(string(b64))

}

Output:

% go run sample.go

float32: 3.1415927
float32: 3.1415927E+00
float32: 13176795p-22
float64: 3.1415926535
float64: 3.1415926535E+00
float64: 3.1416

To learn more about golang, Please refer given below link:

References:

https://golang.org/pkg/

Posted in golang, packages, strconv

Leave a Reply

Your email address will not be published. Required fields are marked *