Python格式十进制数与最小数量的小数位数 [英] Python Format Decimal with a minimum number of Decimal Places

查看:209
本文介绍了Python格式十进制数与最小数量的小数位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python中有一些 Decimal 实例。我希望将它们格式化,使得它们可以用来表示它们:

$ p $ Decimal('1')=> '1.00'
十进制('12.0')=> '12.00'
十进制('314.1')=> '314.10'
十进制('314.151')=> '314.151'

因此确保至少有两位小数,可能更多。尽管对 n 小数位进行四舍五入的解决方案并不缺乏,但是我不能找到确保数字下限的方法。



我现在的解决方案是计算:

$ $ $ $ $ $ $ $ $ $ $ $'$'格式(d)
second ='{:.2f}'。格式(d)

两个更长。但是,它似乎有点hackish。

解决方案

如果您希望避免字符串问题:

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

未经测试的代码,但应 。 b
$ b

这样工作就像这样:

12.345




1234.5



减去int(1234.5)

1234.5 - 1234 = 0.5

<5> .5!= 0



这意味着有3或更多的小数位。

print str(12.345)

即使你做12.3405:



1234.05 - 1234 = .05

<.05!= 0


但是如果你有12.3:

1230 - 1230 = 0

这意味着用%.2f打印。


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.

解决方案

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.

这篇关于Python格式十进制数与最小数量的小数位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆