Chris Seymour
Chris Seymour

Reputation: 85795

Formatting a tuple of floats

How can I format a tuple of float to .3f?

In [1]: pi=3.14159265359

In [2]: print "{:.3f}".format(pi)
3.142

In [3]: e=2.71828182

In [4]: z=(pi,e)

In [5]: print z
(3.14159265359, 2.71828182)

Upvotes: 6

Views: 7901

Answers (2)

RolfBly
RolfBly

Reputation: 3862

You could use

print '{:.3f} {:.3f}'.format(*z)

Upvotes: 7

Martijn Pieters
Martijn Pieters

Reputation: 1122172

You format each float value in the tuple:

print ' '.join(format(f, '.3f') for f in z)

I used the format() function here to achieve the same formatting for individual floating point values.

Output:

>>> pi=3.14159265359
>>> e=2.71828182
>>> z=(pi,e)
>>> print ' '.join(format(f, '.3f') for f in z)
3.142 2.718

Adjust the join string as needed.

Upvotes: 8

Related Questions