Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

golang
strconv
communitycreator

How to use the strconv.ParseComplex() function in Go

Maria Elijah

The strconv.ParseComplex() function

The 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 for complex64, and 128 is used for complex128.

Syntax

func ParseComplex(s string, bitSize int) (complex128, error)

Parameters

  • 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.

Return value

The strconv.ParseComplex() function returns the complex number converted from the given string.

Example

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))
}

Explanation

  • 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

golang
strconv
communitycreator
RELATED COURSES

View all Courses

Keep Exploring