How to use the strconv.FormatFloat() function in Golang
Overview
The FormatFloat() function in the strconv package is used to convert a given floating-point number f to a string.
The formatting is done using the format fmt and precision prec parameters.
Syntax
func FormatFloat(f float64, fmt byte, prec, bitSize int) string
Parameters
f: The floating-point number to be converted in the string form.fmt: A byte value to specify the format.
'b' (-ddddp±ddd, a binary exponent),
'e' (-d.dddde±dd, a decimal exponent),
'E' (-d.ddddE±dd, a decimal exponent),
'f' (-ddd.dddd, no exponent),
'g' ('e' for large exponents, 'f' otherwise),
'G' ('E' for large exponents, 'f' otherwise),
'x' (-0xd.ddddp±ddd, a hexadecimal fraction and binary exponent), or
'X' (-0Xd.ddddP±ddd, a hexadecimal fraction and binary exponent).
prec: The precision value that determines the number of digits printed by thee,E,f,g,G,x, andXformats (excluding the exponent).precis the number of digits after the decimal point for the format value (e,E,f,x, andX).bitSize: An integer value to define thebitSizebits (32forfloat32,64forfloat64).
Return value
The function FormatFloat() returns the given floating-point in the string format.
Code
The following code shows how to use the strconv.FormatFloat() in Golang:
// Using strconv.FormatFloat() Functionpackage mainimport ("fmt""strconv""reflect")func main() {// declaring variablevar num float64// Assign valuenum = 26.345// returns a string typefmt.Println(strconv.FormatFloat(num, 'f', 0, 64))fmt.Println(reflect.TypeOf(strconv.FormatFloat(num, 'f', 0, 64))) // print the typefmt.Println()// reassign valuenum = -17.96// returns a string typefmt.Println(strconv.FormatFloat(num, 'G', 2, 64))fmt.Println()// reassign valuenum = 0.235// returns a string typefmt.Println(strconv.FormatFloat(num, 'E', -1, 64))}
Code explanation
- Line 4: we add the
mainpackage. - Lines 6 to 9: we import the necessary packages.
- Lines 11 to 31: we define the
main()function, variable num ofFloat64type, and assign a value to it. Next, we pass the variable to theFormatFloat()function which converts the num value to a string given thefmt,prec, andbitSizeparameters.