How to use the strconv.FormatComplex() function in Golang
Overview
In Golang, the FormatComplex() function of the strconv package is used to convert a given complex number, c, to a string of the form (a+bi), where a is the real part and b is the imaginary component of the complex number.
The formatting is done using the format fmt and precision prec.
Syntax
Let’s view the syntax of this function.
func FormatComplex(
c complex128,
fmt byte,
prec, bitSize int) string
Parameters
c: The complex number to be converted in the string form.fmt: A byte value to define 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 specifies the number of digits printed by the'e','E','f','g','G','x', and'X'formats. -
bitSize: An integer value that specifies the bitSize bits—64 for the complex64 and 128 for the complex128.
Return value
This function returns the given complex number in the string format (a+bi).
Example
// Using strconv.FormatComplex() Functionpackage mainimport ("fmt""strconv")func main() {// declaring variablevar num complex128// complex value in the form (a+bi)//to be convertednum = complex(5, 3)// returns a string typefmt.Println(strconv.FormatComplex(num, 'f', 0, 64))fmt.Println()// reassign valuenum = complex(2.3, 7.91)// returns a string typefmt.Println(strconv.FormatComplex(num, 'G', 2, 64))fmt.Println()// reassign valuenum = complex(2, 3)// returns a string typefmt.Println(strconv.FormatComplex(num, 'E', -1, 128))fmt.Println()}
Explanation
- Line 4: We add the
mainpackage. - Line 6–9: We import the necessary packages.
- Line 11–31: We define the
main()function, variablenumof Complex128 type and assign a value to it using the functioncomplex(). Next, we pass the variable to theFormatComplex()function, which converts thenumvalue to a string.