Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

python - Limited digits with str.format(), and then only when they matter

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...