Formatting Complex Numbers

前端 未结 5 645
粉色の甜心
粉色の甜心 2020-12-10 11:30

For a project in one of my classes we have to output numbers up to five decimal places.It is possible that the output will be a complex number and I am unable to figure out

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-10 12:00

    Neither String Formatting Operations - i.e. the modulo (%) operator) - nor the newer str.format() Format String Syntax support complex types. However it is possible to call the __format__ method of all built in numeric types directly. Here is an example:

    >>> i = -3 # int
    >>> l = -33L # long (only Python 2.X)
    >>> f = -10./3 # float
    >>> c = - 1./9 - 2.j/9 # complex
    >>> [ x.__format__('.3f') for x in (i, l, f, c)]
    ['-3.000', '-33.000', '-3.333', '-0.111-0.222j']
    

    Note, that this works well with negative imaginary parts too.

提交回复
热议问题