简体   繁体   中英

python format with leading zeros and sign

I'm trying to format float numbers with left leading zeros and sign, but can't find a way to combine operators:

I need this:

-153.3 --> -00000153.30

I'm using this expression:

"{value:0>+{width}.{precision}f}".format(value=float(-153.3), width=12, precision=2)

But I'm getting this: 00000-153.30

Can't find the right way to put the "+" operator, can anyone help?

Thank you

-153.3 --> 00000153.30

If the final numeric string should always be unsigned, why not just use abs() function:

val=-153.3
print("{value:0>{width}.{precision}f}".format(value=abs(val), width=11, precision=2))

The output:

00000153.30
>>> a = -153.3
>>> str(a).zfill(10)
'-0000153.3'

If you want to print positive signs as well, one solution might be:

>>> a = +153.3
>>> '{0:+}'.format(a).zfill(10)
'+0000153.3'

The latter one also works for negative signs.

Got it!

Reading carefully the doc as I should have done!

"{value:+0{width}.{precision}f}".format(value=float(-153.3), width=12, precision=2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM