简体   繁体   English

Python格式十进制,具有最小数量的小数位数

[英]Python Format Decimal with a minimum number of Decimal Places

I have some Decimal instances in Python. 我在Python中有一些Decimal实例。 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. 虽然不存在舍入到n个小数位的解决方案,但我找不到确保数字下限的简洁方法。

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. 然而,它看起来有点hackish。

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 d = 12.345

Times 100: 时代100:

1234.5 1234.5

Minus int(1234.5) 减去int(1234.5)

1234.5 - 1234 = .5 1234.5 - 1234 = .5

.5 != 0 .5!= 0

This means that there are 3 or more decimal places. 这意味着有3个或更多小数位。

print str(12.345) print str(12.345)

Even if you do 12.3405: 即使你做12.3405:

1234.05 - 1234 = .05 1234.05 - 1234 = .05

.05 != 0 .05!= 0

But if you have 12.3: 但是如果你有12.3:

1230 - 1230 = 0 1230 - 1230 = 0

This means to print with %.2f. 这意味着使用%.2f进行打印。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM