Debian Codegraph @

src/internal/strconv/ctoa.go

raw
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
5 package 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.
14 func FormatComplex(c complex128, fmt byte, prec, bitSize int) string {
15 var buf [64]byte
16 return string(AppendComplex(buf[:0], c, fmt, prec, bitSize))
17 }
18
19 // AppendComplex appends the result of FormatComplex to dst.
20 // It is here for the runtime.
21 // There is no public strconv.AppendComplex.
22 func AppendComplex(dst []byte, c complex128, fmt byte, prec, bitSize int) []byte {
23 if bitSize != 64 && bitSize != 128 {
24 panic("invalid bitSize")
25 }
26 bitSize >>= 1 // complex64 uses float32 internally
27
28 dst = append(dst, '(')
29 dst = AppendFloat(dst, real(c), fmt, prec, bitSize)
30 i := len(dst)
31 dst = AppendFloat(dst, imag(c), fmt, prec, bitSize)
32 // Check if imaginary part has a sign. If not, add one.
33 if dst[i] != '+' && dst[i] != '-' {
34 dst = append(dst, 0)
35 copy(dst[i+1:], dst[i:])
36 dst[i] = '+'
37 }
38 dst = append(dst, "i)"...)
39 return dst
40 }