How to Print only 4 decimal places in python?

Question:

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,

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

Asked By: Muhammad Umar

||

Answers:

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
Answered By: Divyessh

Another way to accomplish the desired output. Note, the rounded value will be of type str:

from math import *

x = -pi
h = 0.001
while x <= pi:
    print("d/dx sin(x) =  sin(x+h) - sin(x) / h :", "%.4f" % ((sin(x + h) - sin(x)) / h))
    print("d/dx sin(x) = cos(x): ", "%.4f" % cos(x))
    x += h
Answered By: irahorecka

use f-string and .4f like this:

print(f"{0.123456789:.4f}")
Answered By: jonas
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.