0

Following Printing tuple with string formatting in Python, I'd like to print the following tuple:

tup = (0.0039024390243902443, 0.3902439024390244, -0.005853658536585366, -0.5853658536585366)

with only 5 digits of precision. How can I achieve this?

(I've tried print("%.5f" % (tup,)) but I get a TypeError: not all arguments converted during string formatting).

Community
  • 1
  • 1
Kurt Peek
  • 43,920
  • 71
  • 247
  • 451
  • 1
    Tuples don't have precision, floats do. And you're trying to convert a tuple to a float, which doesn't make any sense. – Wayne Werner Aug 22 '16 at 12:58

9 Answers9

1

You can print the floats with custom precision "like a tuple":

>>> tup = (0.0039024390243902443, 0.3902439024390244, -0.005853658536585366, -0.5853658536585366)
>>> print('(' + ', '.join(('%.5f' % f) for f in tup) + ')')
(0.00390, 0.39024, -0.00585, -0.58537)
L3viathan
  • 25,498
  • 2
  • 53
  • 71
0

try the following (list comprehension)

['%.5f'% t for t in tup]
Mohammad Athar
  • 1,825
  • 1
  • 14
  • 30
0

Try this:

class showlikethis(float):
    def __repr__(self):
        return "%0.5f" % self

tup = (0.0039024390243902443, 0.3902439024390244, -0.005853658536585366, -0.5853658536585366)
tup = map(showlikethis, tup)
print tup

You may like to re-quote your question, tuple dnt have precision.

PradyJord
  • 2,046
  • 11
  • 18
  • o the one who down voted, the mighty intelligent being: a small comment with little explanation would have helped us. – PradyJord Aug 22 '16 at 13:05
0

you can work on single item. Try this:

>>> tup = (0.0039024390243902443, 0.3902439024390244, -0.005853658536585366, -0.5853658536585366)
>>> for t in tup:
    print ("%.5f" %(t))


0.00390
0.39024
-0.00585
-0.58537
Harsha Biyani
  • 6,633
  • 9
  • 33
  • 55
0

You can iterate over tuple like this, and than you can print result for python > 3

["{:.5f}".format(i) for i in tup] 

And for python 2.7

['%.5f'% t for t in tup]
wolendranh
  • 3,994
  • 1
  • 26
  • 37
0

Possible workaround:

tup = (0.0039024390243902443, 0.3902439024390244, -
       0.005853658536585366, -0.5853658536585366)

print [float("{0:.5f}".format(v)) for v in tup]
BPL
  • 9,532
  • 7
  • 47
  • 105
0

Most Pythonic way to achieve this is with map() and lambda() function.

>>> map(lambda x: "%.5f" % x, tup)
['0.00390', '0.39024', '-0.00585', '-0.58537']
Moinuddin Quadri
  • 43,657
  • 11
  • 92
  • 117
0

I figured out another workaround using Numpy:

import numpy as np
np.set_printoptions(precision=5)
print(np.array(tup))

which yields the following output:

[ 0.0039   0.39024 -0.00585 -0.58537]
Kurt Peek
  • 43,920
  • 71
  • 247
  • 451
0

Here's a convenient function for python >3.6 to handle everything for you:

def tuple_float_to_str(t, precision=4, sep=', '):
    return '({})'.format(sep.join(f'{x:.{precision}f}' for x in t))

Usage:

>>> print(funcs.tuple_float_to_str((12.3456789, 8), precision=4))
(12.3457, 8.0000)
Mateen Ulhaq
  • 21,459
  • 16
  • 82
  • 123