Quixotic
Quixotic

Reputation: 2464

Precision in python

How can write a print statement in python that will print exactly 2 digits after decimal?

Upvotes: 6

Views: 19344

Answers (5)

Satyam Zode
Satyam Zode

Reputation: 185

Another efficient way of doing this is:

import sys
a = 0.5
sys.stdout.write(str('%0.2f'%a))

Upvotes: 0

Pythoni
Pythoni

Reputation: 294

this is django float format template tag, that may be interest for you to reading ...

at line 92 :

django float format template tag

Upvotes: 0

Maciej Ziarko
Maciej Ziarko

Reputation: 12114

 f = 4.55556
 print "{0:.2f}".format(f)

There is also a special module for fixed point decimals. More: http://docs.python.org/library/decimal.html

Upvotes: 3

Björn Pollex
Björn Pollex

Reputation: 76876

print "{0:.2f}".format(your_number)

This is explained in detail in the Python Documentation.

Upvotes: 13

Rafe Kettler
Rafe Kettler

Reputation: 76965

x = 4.12121212
print '%.2f' % x

Basically, the same way you'd do it in C with printf.

Upvotes: 6

Related Questions