fred basset
fred basset

Reputation: 10082

Python, want to print float in exact format +-00.00

I need to format a float to the format +-00.00, tried the basic string formatting but can't get the leading + or - sign or two leading 0s if the value is fractional, any pointers?

Upvotes: 14

Views: 18409

Answers (3)

Joachim Isaksson
Joachim Isaksson

Reputation: 180917

'%+06.2f' % 1.1123344

+ means always use sign
0 means zero fill to full width.
6 is the total field width including sign and decimal point
.2 means 2 decimals.
f is float

Upvotes: 16

Kartik
Kartik

Reputation: 9853

Using this should do it

x = 50.4796
a = -50.1246

print " %+2.2f" % (x)
print " %+2.2f" % (a)

The following should print

+50.48
-50.12

Upvotes: 0

Marcelo Cantos
Marcelo Cantos

Reputation: 185852

Use '%+06.2f' to set the width and precision appropriately. The equivalent using new-style format strings is '{:+06.2f}'.format(n) (or '{0:+06.2f}' if your version of Python requires the positional component).

Upvotes: 15

Related Questions