Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append a plus sign before positive numbers?

Tags:

python

printf

I'm printing floats trimmed to 3 digits after the zero, and I'd like to know if I can conditionally append a + before positive numbers, so I get

+0.005

for a positive change and

-0.005

for a negative change. Is this easily possible from within printf?

like image 691
Naftuli Kay Avatar asked Jan 11 '12 22:01

Naftuli Kay


2 Answers

Yes, just use a '+' in the format specifier.

Ex:

>>> "{0:+.03f}".format(1.23456)
'+1.235'
like image 148
Gavin H Avatar answered Sep 19 '22 06:09

Gavin H


There's a + modifier for numbers. Eg. "%+d" or "%+f"

like image 27
Ricardo Cárdenes Avatar answered Sep 18 '22 06:09

Ricardo Cárdenes