Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

If we're printing a dollar amount, we usually want to always display two decimal digits.

cost1, cost2 = 123.456890123456789, 357.000
print '{c1:.2f}  {c2:.2f}'.format(c1=cost1, c2=cost2)

shows

123.46  357.00

But on other occasions we'd like to print the fractions only if they matter. If the two numbers above were volume, for instance, we may prefer to display

123.45 gal. 357 gal.

Can this be obtained directly with format?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
168 views
Welcome To Ask or Share your Answers For Others

1 Answer

In String Formatting Operations Python Docs describe the %g format which truncates trailing zeros.

>>> print "%g gallons" % (123.45)
123.45 gallons

>>> print "%g gallons" % (357)
357 gallons

>>> print "%g gallons" % (357.0)
357 gallons

Or using Python 3 string formatting:

>>> print "{:g} gal {:g} gal".format(123.45, 357.0)
123.45 gal 357 gal

The g formatter is unintuitive but you can get some interesting results by setting the precision:

>>> print "{:g} gal {:.3g} gal {:.4g} gal {:.5g} gal {:.6g} gal {:.7g} gal".format(*([123.456789] * 6))
123.457 gal 123 gal 123.5 gal 123.46 gal 123.457 gal 123.4568 gal

Note that in this case setting precision to .5 achieves the desired result of 2 decimal places.

Of course you could combine this with f floating point formatter first to get whatever you wanted.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...