1// Copyright 2020 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5package strconv
6
7// FormatComplex converts the complex number c to a string of the
8// form (a+bi) where a and b are the real and imaginary parts,
9// formatted according to the format fmt and precision prec.
10//
11// The format fmt and precision prec have the same meaning as in [FormatFloat].
12// It rounds the result assuming that the original was obtained from a complex
13// value of bitSize bits, which must be 64 for complex64 and 128 for complex128.
14func FormatComplex(c complex128, fmt byte, prec, bitSize int) string {
15	if bitSize != 64 && bitSize != 128 {
16		panic("invalid bitSize")
17	}
18	bitSize >>= 1 // complex64 uses float32 internally
19
20	// Check if imaginary part has a sign. If not, add one.
21	im := FormatFloat(imag(c), fmt, prec, bitSize)
22	if im[0] != '+' && im[0] != '-' {
23		im = "+" + im
24	}
25
26	return "(" + FormatFloat(real(c), fmt, prec, bitSize) + im + "i)"
27}
28