-1

how to print out no more than two decimal digits of accuracy like 5.32 instead of 5.32436675? Is there any keyword regarding this in python.

  • 1
    I recommend getting to know the [Python String Formatting](http://docs.python.org/2/library/stdtypes.html#string-formatting) section of the Python docs. Lots of great stuff in there. – Christian Ternus Nov 01 '13 at 17:38
  • By the way, do you want to round or just truncate? – Christian Tapia Nov 01 '13 at 17:40
  • As Christian said, Python String Formatting is very useful. If you want to round, however, python string formatting will give you problems. My answer is about rounding, that that's what you want to do. His answer is about string formatting, if that's what you want to do-- Go with whichever one applies. – jwarner112 Nov 01 '13 at 17:43
  • @Christian As evidenced by his using *accuracy*, I think he might have wanted rounding? – jwarner112 Nov 01 '13 at 17:45

5 Answers5

5

Try:

a = 5.32436675
print("%.2f" % a)

Remember this is rounding.

If you just want to truncate use this method from this post.

def trunc(f, n):
    '''Truncates/pads a float f to n decimal places without rounding'''
    slen = len('%.*f' % (n, f))
    return str(f)[:slen]

print(trunc(a, 2))
Community
  • 1
  • 1
Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
1

You want to round to 2 places, as seen below:

round(number, 2)

Example:

round(5.32436675, 2)

Output:

5.32

This is preferable to float implementations (truncating solutions) because the rounding means the number is still mostly accurate. You don't want 5.319 to get cut off to 5.31 when it should be 5.32!

Happy coding!

jwarner112
  • 1,492
  • 2
  • 14
  • 29
0

You can use:

n = 23.232323
print "%.2f" % n 

The '.2' here indicates 2 digits after the decimal point.

Fraser Graham
  • 4,650
  • 4
  • 22
  • 42
Raydel Miranda
  • 13,825
  • 3
  • 38
  • 60
0

According to string format specifications :

>>> "{0:.2f}".format(5.32436675)
5.32
Sudipta
  • 4,773
  • 2
  • 27
  • 42
0

% formatting is getting a bit old. The new way:

print('{:.2f}'.format(5/9))
dstromberg
  • 6,954
  • 1
  • 26
  • 27