简体   繁体   中英

Format print value as percentage in python

I have this code:

if SPEED <= 0.0129:
    seqSpeed = (SPEED / 100.0) * 15.5
    print("Speed: {:1.0%}".format(seqSpeed))

Instead of showing Speed: 20%

It shows Speed: 1%%%

What can I do to fix it?

The % specifier multiplies the value by a hundred then acts as if you'd used the f specifier.

Since your maximum SPEED here is 0.0129 (as per the if statement), your formula (SPEED / 100.0) * 15.5 will generate, at most, 0.0019995 . The % specifier will then turn that into 0.19995 , which is only about 0.2% .

If you're expecting it to give you 20% , you need to get rid of the / 100.0 bit from your formula. That way, you'll end up with 0.19995 , the % specifier will change that to 19.995 , and you should then get 20% by virtue of the fact you're using 1.0 as the width specification, as per the following transcript:

>>> SPEED = 0.0129
>>> seqSpeed = SPEED * 15.5
>>> print("Speed: {:1.0%}".format(seqSpeed))
Speed: 20%

Use f-strings instead:

if SPEED <= 0.0129:
    seqSpeed = (SPEED / 100.0) * 15.5
    print(f'Speed: {seqSpeed}')

And if you need to use .format() :

print('Speed: {0}'.format(seqSpeed))

And also there is:

print('Speed: %s' % x)

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