TPQ
TPQ

Reputation: 53

How to get right decimals as output in simple fraction

When I write

print("{:.4f}".format(333/106))

I get the output

3.000

but when i try

print("{:.4f}".format(3.14159))

I get

3.1416

How can I get the correct decimals for the fraction ?

Upvotes: 0

Views: 39

Answers (2)

Valdi_Bo
Valdi_Bo

Reputation: 30971

You are probably using Python 2.x, where division of two integers gets rounded result. Try to specify at least one number as float, e.g. print("{:.4f}".format(333.0/106)) or print("{:.4f}".format(float(333)/106)).

Upvotes: 1

oreopot
oreopot

Reputation: 3450

Try the following code:

pi = 3.1415926
precision = 4
print( "{:.{}f}".format( pi, precision ) )

Check this link for formatting cheat-sheet

Upvotes: 0

Related Questions