0

Possible Duplicate:
Display a float with two decimal places in Python

How can I force all numbers in python to output two decimal places after them?

E.G.

0.5 should be 0.50

Community
  • 1
  • 1
  • (Please close duplicates as duplicates - absolutely nothing new or exciting here.) –  Nov 10 '12 at 21:07

3 Answers3

7

The format mini language is preferred these days (since the % format operator may be deprecated one day.):

>>> print '{:.2f}'.format(.5)
0.50

Plus, IMHO, string.format() is easier to read.

4
>> print '%.2f' % 0.5
0.50
Nicolas
  • 5,583
  • 1
  • 25
  • 37
1

To print numbers:

print "%.2f" %num

To store numbers in variables:

round(num, 2)
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
  • `round(num,2)` rounds the number which has more than 2 decimal places to 2 decimal places but cannot make a number with 1 decimal place into 2. It cannot make 0.5 into 0.50 – Bharat Nov 10 '12 at 21:10
  • fair point. I didn't know whether OP was asking for printing or for program internal representation. This is why I gave both solutions – inspectorG4dget Nov 10 '12 at 22:35