极其简单的python十进制
你好,我需要一些帮助。我想计算格式为 xxxxx.yyyyyyyyyyyyyyy 的浮点数。我知道我应该使用 Decimal 而不是 float 我尝试了很多,也搜索了很多,但仍然有以下简单问题:
getcontext().prec = 14
a = Decimal(str('12.737791301'))
b = Decimal(str('12.737791839'))
c = Decimal((b - a)) # substract is what I finally want here
print a, b, c
12.737791301 12.737791839 5.38E-7
我希望 c 显示为 0.000000538
感谢您的帮助!
附注Normalize() 不起作用
Hi I need some help please. I want to calculate float numbers with a format like xxxxx.yyyyyyyyyyyyyyy. I have learned that I should use Decimal instead of float
I tried a lot, and I searched a lot but I still have the following simple problem:
getcontext().prec = 14
a = Decimal(str('12.737791301'))
b = Decimal(str('12.737791839'))
c = Decimal((b - a)) # substract is what I finally want here
print a, b, c
12.737791301 12.737791839 5.38E-7
I want c to be displayed as 0.000000538
thanks for your help!
ps. normalize() did not work
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
真正的解决方案是 format(),在 python 2.6 和 3.1 中可用。
format(c,"f")
会将小数转换为浮点 repr 样式输出。这是 python 中新样式格式化的一部分。其他更糟糕的解决方案想法如下:
这可以通过格式字符串来完成,就好像您的 Decimal 值是浮点数一样。
print "%0.9f" % c
将产生 '0.000000538'Python 库参考 可以告诉您更多信息。
为了解决需要知道正确的小数位数的问题,您总是可以在浮点精度的限制下打印出来,并带有一个条件,以防小数较小:
第二行处理尾随 0。
The real solution is format(), available in python 2.6 and 3.1.
format(c,"f")
will convert the decimal to float repr-style output. This is part of the new style formatting in python.Other worse ideas for solutions are below:
This can be accomplished with a format string, as if your Decimal values were floats.
print "%0.9f" % c
will produce '0.000000538'The python library reference can tell you more.
To get around the problem of needing to know the right number of decimal places, you could always print it out at the limit of float precision with a condition in case the Decimal is smaller:
With the second line dealing with the trailing 0s.
您可以使用
量化
。类似于编辑的东西。在您的特定示例中,以下内容有效:
如果您想要更强大的东西,请查找此示例http: //docs.python.org/library/decimal.html#recipes
You may use
quantize
. Something along the lines ofEDIT. In your particular example the following works:
If you want something more robust, look up this example http://docs.python.org/library/decimal.html#recipes