Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 237
fred basset Avatar asked Jan 31 '12 21:01

fred basset


2 Answers

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).

like image 111
Marcelo Cantos Avatar answered Sep 23 '22 07:09

Marcelo Cantos


'%+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
like image 22
Joachim Isaksson Avatar answered Sep 23 '22 07:09

Joachim Isaksson