How to use the strconv.AppendFloat() function in Golang
Golang strconv.AppendFloat()
The strconv package’s AppendFloat() method in Golang is used to append the string form of the specified floating-point number f (as generated by the FormatFloat() function) to dst and return the extended buffer.
The parameter dst is of type []byte and f is of type float64.
Syntax
func AppendFloat(
dst []byte,
f float64,
fmt byte,
prec, bitSize int) []byte
Parameters
dst: This is a byte array to which the floating-point number is to be appended as a string.f: This is the floating-point number to be appended todst.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 forfloat32, 64 forfloat64).
Return value
The function AppendFloat() returns the extended buffer after appending the given floating-point value.
Code
The following code shows how to implement the strconv.AppendFloat() in Golang.
// Using strconv.AppendFloat() Functionpackage mainimport ("fmt""strconv")func main() {// Declaring and assigning valuex := []byte("Some text with a float64: ")fmt.Println("Before AppendFloat():", string(x))// Appending float-point value// prec, fmt, and bitsizex = strconv.AppendFloat(x, 56.37781, 'E', -1, 64)fmt.Println("After AppendFloat():",string(x))fmt.Println()// Declaring and assigning valuey := []byte("Some text with a float64: ")fmt.Println("Before AppendFloat():", string(y))// Appending float-point value// prec, fmt, and bitsizey = strconv.AppendFloat(x, 56.37781, 'g', 2, 32)fmt.Println("After AppendFloat():",string(y))fmt.Println()}
Code explanation
- Line 4: We add the
mainpackage. - Lines 6–9: We import the necessary packages.
- Lines 11–31: We define the
main()function, variablesxandyofFloat64andFloat32type, respectively, and assign a value to each. Next, We pass the variables to theAppendFloat()function which appends the string form of the specified floating-point numberfaccording to thefmt,prec, andbitSizeparameters.