Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to Print only 4 decimal places in python?

I am writing a simple program to verify the formula of derivate and in output I am getting too many decimal places which look awful.

I am pretty new to python. I want to only show four decimal places.

here is my code,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

from math import *

x = -pi
h = 0.001
while x <= pi:
    print("d/dx sin(x) =  sin(x+h) - sin(x) / h :", (sin(x + h) - sin(x)) / h)
    print("d/dx sin(x) = cos(x): ", cos(x))
    x += h

>Solution :

You should use string formatting while printing like this

from math import *

x = -pi
h = 0.001
while x <= pi:
    print("d/dx sin(x) =  sin(x+h) - sin(x) / h :", "{:.4f}".format((sin(x + h) - sin(x)) / h))
    print("d/dx sin(x) = cos(x): ", "{:.4f}".format(cos(x)))
    x += h
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading