Python 十进制模块有助于我们在分割中使用正确的精度和圆形的 [数字]( / 社区 / 教程 / Python - 数字)。
Python 十进制模块
In this lesson on decimal module in Python, we will see how we can manage decimal numbers in our programs for precision and formatting and making calculations as well. The precision with decimal numbers is very easy to lose if numbers are not handled correctly. Let's see how the decimal module and its available functions help in these areas.
用十进制数字工作
十进制数字只是固定十进制点的浮点数字,我们必须根据我们的需求正确地圆形数字,否则结果可能会出乎意料。
需要十进制模块
在实际使用此模块之前,让我们看看我们正在谈论什么样的精度,并确定为什么我们实际上需要这个模块。
1division = 72 / 7
2print(division)
Let's see the output for this program: Well, the answer was not actually accurate and there were no decimal points at all! Let's see how we can correct this by using the decimal module.
使用十进制模块
在我们在本文中制作的所有程序中,我们将在所有程序中导入十进制模块:
1import decimal
我们可能只是从此模块中导入一个特定的函数,可以这样做:
1from decimal import Decimal
让我们开始把十进制模块放入一些程序中。
Python 十进制模块示例
我们现在将开始与模块相关的例子。
用十进制来纠正分数
在这里,我们将纠正我们上面写的程序,以执行应该产生浮点结果的划分。
1import decimal
2
3division = decimal.Decimal(72) / decimal.Decimal(7)
4print(division)
Let's see the output for this program: To notice, the division is correct now and precise as well, or maybe it is too precise?
单一操作的精度控制
在最后一个程序中,现在答案中有25个十进制位。但如果我们只想要多达三个十进制值位?这也可以控制。
1import decimal
2
3with decimal.localcontext() as ctx:
4 ctx.prec = 3
5 division = decimal.Decimal(72) / decimal.Decimal(7)
6 print(division)
7
8again = decimal.Decimal(72) / decimal.Decimal(7)
9print(again)
We did the division operation two times to prove a point. Let's see the output for this program: Noticed something? The precision we set was only valid for a single time. Next time we did the division, we got back the same result.
对完整程序进行精确控制
在程序中也可以在全球范围内控制精度,这不建议在您在程序中处理大量数字时进行。
1import decimal
2
3decimal.getcontext().prec = 3
4
5division = decimal.Decimal(72) / decimal.Decimal(7)
6print(division)
7
8again = decimal.Decimal(72) / decimal.Decimal(7)
9print(again)
Let's see the output for this program:
围绕数字
可以用圆(...)
函数优雅地围绕数字,让我们试试:
1import decimal
2
3#Can be rounded to 13.48 or 13.49
4rounded = round(13.485, 2)
5print(rounded)
Let's see the output for this program: The number in program can be rounded to 13.48 or 13.49. By default, the
round(...)
function rounds down. This can be changed as well:
1import decimal
2
3#Can be rounded to 13.48 or 13.49
4rounded = round(13.485, 2)
5print(decimal.Decimal(rounded).quantize(decimal.Decimal('0.00'), rounding=decimal.ROUND_UP))
Let's see the output for this program:
获取 Python 十进制背景
如果您有兴趣查看为十进制模块默认设置的默认环境,您可以使用以下脚本:
1from decimal import *
2print(getcontext())
Let's see the output for this program: That's all for python decimal module, it's very useful when working with float point numbers.