Python Format Decimal with a minimum number of Decimal Places

孤者浪人 提交于 2019-12-10 15:01:33

问题


I have some Decimal instances in Python. I wish to format them such that

Decimal('1')       => '1.00'
Decimal('12.0')    => '12.00'
Decimal('314.1')   => '314.10'
Decimal('314.151') => '314.151'

hence ensuring that there are always at least two decimal places, possibly more. While there are no shortage of solutions for rounding to n decimal places I can find no neat ways of ensuring a lower bound on the number.

My current solution is to compute:

first  = '{}'.format(d)
second = '{:.2f}'.format(d)

and take which ever of the two is longer. However it seems somewhat hackish.


回答1:


If you wish to avoid string issues:

if d*100 - int(d*100):
    print str(d)
else:
    print ".2f" % d

Untested code, but it should work.

This works like so:

d = 12.345

Times 100:

1234.5

Minus int(1234.5)

1234.5 - 1234 = .5

.5 != 0

This means that there are 3 or more decimal places.

print str(12.345)

Even if you do 12.3405:

1234.05 - 1234 = .05

.05 != 0

But if you have 12.3:

1230 - 1230 = 0

This means to print with %.2f.



来源:https://stackoverflow.com/questions/11181295/python-format-decimal-with-a-minimum-number-of-decimal-places

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