I want to round the complex and real part upto 2 decimal points. How can I do that in python?
angle = 2 * np.pi *2 c1 = complex(np.cos(angle),np.sin(angle)) c1 = round(c1,2) You noted in a comment:
I have t use these complex numbers in a matrix. In order to read it easily I want to display it upto 2 decimal points
So how about modifying the printing of your data, rather than messing with their representation as data? You only need to set_printoptions with a formatter for complex numbers:
>>> import numpy as np >>> arr = np.random.rand(3,3) + 1j*np.random.rand(3,3) ... print(arr) [[0.44078748+0.29907718j 0.79358223+0.02234568j 0.20919567+0.34527526j] [0.05402969+0.24115898j 0.20941358+0.55299497j 0.29743888+0.32179154j] [0.60174937+0.9542182j 0.47197093+0.9202769j 0.41205623+0.27288905j]] >>> np.set_printoptions(formatter={'complex_kind': '{:.2f}'.format}) >>> print(arr) [[0.44+0.30j 0.79+0.02j 0.21+0.35j] [0.05+0.24j 0.21+0.55j 0.30+0.32j] [0.60+0.95j 0.47+0.92j 0.41+0.27j]] I think you can use the around function from numpy:
import numpy x= complex(1.2345, 1.2345) numpy.around(x, 2) # (1.23+1.23j)
f"{c1:.2}"or"{:.2}".format(c1).complex(round(c1.real,2), round(c1.imag, 2))x = complex(round(x.real,2), round(x.imag,2)).2rounds it to a precision of two (e.g.,1.23is rounded to1.2), not two decimal places..2fcould be considered instead.