Most Pythonic way to print *at most* some number of decimal places [duplicate]

◇◆丶佛笑我妖孽 提交于 2019-11-27 02:14:10

You need to separate the 0 and the . stripping; that way you won't ever strip away the natural 0.

Alternatively, use the format() function, but that really comes down to the same thing:

format(f, '.2f').rstrip('0').rstrip('.')

Some tests:

>>> def formatted(f): return format(f, '.2f').rstrip('0').rstrip('.')
... 
>>> formatted(0.0)
'0'
>>> formatted(4.797)
'4.8'
>>> formatted(4.001)
'4'
>>> formatted(13.577)
'13.58'
>>> formatted(0.000000000000000000001)
'0'
>>> formatted(10000000000)
'10000000000'

The g formatter limits the output to n significant digits, dropping trailing zeroes:

>>> "{:.3g}".format(1.234)
'1.23'
>>> "{:.3g}".format(1.2)
'1.2'
>>> "{:.3g}".format(1)
'1'

In general working with String[s] can be slow. However, this is another solution:

>>> from decimal import Decimal
>>> precision = Decimal('.00')
>>> Decimal('4.001').quantize(precision).normalize()
Decimal('4')
>>> Decimal('4.797').quantize(precision).normalize()
Decimal('4.8')
>>> Decimal('8.992').quantize(precision).normalize()
Decimal('8.99')
>>> Decimal('13.577').quantize(precision).normalize()
Decimal('13.58')

You may find more info here: http://docs.python.org/2/library/decimal.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!