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
.
Let’s view the syntax of this function.
func FormatComplex(
c complex128,
fmt byte,
prec, bitSize int) string
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.
This function returns the given complex number in the string format (a+bi)
.
// 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()}
main
package.main()
function, variable num
of Complex128 type and assign a value to it using the function complex()
. Next, we pass the variable to the FormatComplex()
function, which converts the num
value to a string.