首页 > 编程技术 > python

Python decimal模块的使用示例详解

发布时间:2023-3-14 16:27 作者:River Chandler

Python decimal 模块

getcontext函数

#在context中设置小数的精度
decimal.getcontext().prec = 100

因为通过浮点数初始化Decimal类型的变量会导致精度的丢失

# 浮点数的初始化
a = decimal.Decimal('3.14159265')

setcontext函数

decimal.ROUND_HALF_UP 对浮点数四舍五入

import decimal
x = decimal.Decimal('1.23456789')
context = decimal.Context(prec=4,rounding=decimal.ROUND_HALF_UP)
decimal.setcontext(context)
y1 = x
y2 = x*2 
print("y1",y1)
print("y2",y2)
 
>>>y1 1.23456789
>>>y2 2.469

localcontext函数

import decimal
x = decimal.Decimal('1.23456789')
context0 = decimal.Context(prec=9,rounding=decimal.ROUND_HALF_UP)
decimal.setcontext(context0)
y1 = x * 2
print("y1",y1)
 
with decimal.localcontext() as context:
    context.prec = 4
    context.rounding = decimal.ROUND_HALF_UP
    y2 = x * 2
    print("y2",y2)
 
 
>>>y1 2.46913578
>>>y2 2.469
>>>
>>>

到此这篇关于Python decimal模块的使用的文章就介绍到这了,更多相关Python decimal使用内容请搜索猪先飞以前的文章或继续浏览下面的相关文章希望大家以后多多支持猪先飞!

原文出处:https://blog.csdn.net/Chandler_river/article/details/1294474

标签:[!--infotagslink--]

您可能感兴趣的文章: