简体   繁体   中英

Print leading zeros of a floating point number

I am trying to print something:

>>> print "%02i,%02i,%02g" % (3, 4, 5.66)
03,04,5.66

However this is not correct. If you notice, the zeroes get correctly pre-pended to all the integer floating points (the first two numbers). I need it such that there will be one leading zero if the there is a single digit to the left of the decimal point.

Ie the solution above should return:

03,04,05.66

What am I doing wrong?

For g , specify and width and precision:

>>> print "%02i,%02i,%05.3g" % (3, 4, 5.66)
03,04,05.66

f versus g

The difference between f and g is illustrated here:

>>> print "%07.1f, %07.1f, %07.1f" % (1.23, 4567.8, 9012345678.2)
00001.2, 04567.8, 9012345678.2
>>> print "%07.1g, %07.1g, %07.1g" % (1.23, 4567.8, 9012345678.2)
0000001, 005e+03, 009e+09

When given large numbers, g switches to scientific notation while f just uses more spaces.

Similarly, g switches to scientific notation, when needed, for small numbers:

>>> print "%07.1f, %07.1f, %07.1f" % (.01, .0001, .000001)
00000.0, 00000.0, 00000.0
>>> print "%07.1g, %07.1g, %07.1g" % (.01, .0001, .000001)
0000.01, 00.0001, 001e-06

Use different format ie f :

print "%02i,%02i,%05.2f" % (3, 4, 5.66)
                 ^^^^^^

or with g :

    print "%02i,%02i,%05.3g" % (3, 4, 5.66)
                     ^^^^^^

But I would stick to f . I guess that's what you trying to do here ( g can sometimes use decimal format). More info here: formatting strings with %

'f' Floating point decimal format.
'g' Floating point format. Uses lowercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise.

The format %02g specifies minimum width of 2. You can use %0m.n syntax where m is the minimum width and n is the number of decimals. What you need is this:

>>> print "%02i,%02i,%05.2f" % (3, 4, 5.66)
03,04,05.66

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