Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You could do it as is shown below using the <code>str.format()</code> method:</p> <pre class="lang-none prettyprint-override"><code>&gt;&gt;&gt; n = 3.4+2.3j &gt;&gt;&gt; n (3.4+2.3j) &gt;&gt;&gt; '({0.real:.2f} + {0.imag:.2f}i)'.format(n) '(3.40 + 2.30i)' &gt;&gt;&gt; '({c.real:.2f} + {c.imag:.2f}i)'.format(c=n) '(3.40 + 2.30i)' </code></pre> <p>To make it handle both positive and negative imaginary portions properly, you would need a (even more) complicated formatting operation:</p> <pre class="lang-none prettyprint-override"><code>&gt;&gt;&gt; n = 3.4-2.3j &gt;&gt;&gt; n (3.4-2.3j) &gt;&gt;&gt; '({0:.2f} {1} {2:.2f}i)'.format(n.real, '+-'[n.imag &lt; 0], abs(n.imag)) '(3.40 - 2.30i)' </code></pre> <p><strong>Update - Easier Way</strong></p> <p>Although you <strong>cannot</strong> use <code>f</code> as a presentation type for complex numbers using the string formatting operator <code>%</code>:</p> <pre><code>n1 = 3.4+2.3j n2 = 3.4-2.3j try: print('test: %.2f' % n1) except Exception as exc: print('{}: {}'.format(type(exc).__name__, exc)) </code></pre> <p>Output:</p> <pre class="lang-none prettyprint-override"><code> TypeError: float argument required, not complex </code></pre> <p>You <strong>can</strong> however use it with complex numbers via the <code>str.format()</code> method. This isn't explicitly documented, but is implied by the <a href="https://docs.python.org/3/library/string.html?highlight=formatting#format-specification-mini-language" rel="nofollow noreferrer">Format Specification Mini-Language</a> documentation which just says:</p> <blockquote> <p><code>'f'</code>&nbsp;&nbsp;Fixed point. Displays the number as a fixed-point number. The default precision is <code>6</code>.</p> </blockquote> <p>. . .so it's easy to overlook. In concrete terms, the following works in both Python 2.7.14 and 3.4.6:</p> <pre><code>print('n1: {:.2f}'.format(n1)) print('n2: {:.2f}'.format(n2)) </code></pre> <p>Output:</p> <pre class="lang-none prettyprint-override"><code>n1: 3.10+4.20j n2: 3.10-4.20j </code></pre> <p>This doesn't give you quite the control the code in my original answer does, but it's certainly much more concise (and handles both positive and negative imaginary parts automatically).</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload