strconv.ParseComplex()
functionThe ParseComplex()
function is a strconv
package inbuilt function that converts a string s
to a complex number with the precision defined by bitSize
.
Note: The value of
bitSize
must be 64 or 128. 64 is used forcomplex64
, and 128 is used forcomplex128
.
func ParseComplex(s string, bitSize int) (complex128, error)
s
: The string value to be converted to a complex number.
bitSize
: It is used to specify the precision. The value can be 64 or 128.
The strconv.ParseComplex()
function returns the complex number converted from the given string.
The following code shows how to implement the strconv.ParseComplex()
function in Go.
// Golang program // using strconv.ParseComplex() Function package main import ( "fmt" "strconv" ) func main() { // function converts the str variable // to a complex number with the precision // defined by bitSize. // declare variable str as string var str string // assign value str = "2-3i" // function converts the str variable // to a complex number with the precision // defined by bitSize. // then display result fmt.Println(strconv.ParseComplex(str, 64)) fmt.Println(strconv.ParseComplex(str, 128)) fmt.Println() // reassign value str = "√5 + √2i" // function converts the str variable // to a complex number with the precision // defined by bitSize. // then display result fmt.Println(strconv.ParseComplex( str, 64)) fmt.Println(strconv.ParseComplex(str, 128)) fmt.Println() // reassign value str = "2.56+3.192i" // function converts the str variable // to a complex number with the precision // defined by bitSize. // then display result fmt.Println(strconv.ParseComplex(str, 64)) fmt.Println(strconv.ParseComplex(str, 128)) }
Line 4: We add the main
package.
Line 6–9: We import the necessary packages.
Line 11–21: We define the main()
function, variable str
of string type and assign a value to it. We pass the variable to the ParseComplex()
function which converts the str
variable to a complex number with the precision defined by bitSize
.
Finally, we display the result.
RELATED TAGS
CONTRIBUTOR
View all Courses