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

I need to format the float in the format + -00.00, tried formatting the main line, but I can’t get the + or - sign or the two leading 0s, if the value is fractional, any pointers?

+5
source share
3 answers

Use '%+06.2f'to set width and accuracy correctly. Equivalent to using new-style strings '{:+06.2f}'.format(n)(or '{0:+06.2f}'if your version of Python requires a positional component).

+6
source

'% + 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
+8
source

Using it, you need to do it

x = 50.4796
a = -50.1246

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

The following should print

+50.48
-50.12
0
source

All Articles