1.创建Decimal对象
from decimal import Decimal # 创建一个Decimal对象 d = Decimal('3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679') # 输出Decimal对象 print(d) #3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679
2.设置全局精度
import decimal # 设置全局精度为10位 decimal.getcontext().prec = 10 # 创建两个Decimal对象 a = Decimal('0.1') b = Decimal('0.2') # 输出两个数的和 print(a + b) #0.3000000000
3.四舍五入
from decimal import Decimal, ROUND_HALF_UP # 创建一个Decimal对象 d = Decimal('3.14159') # 四舍五入保留两位小数 d = d.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP) # 输出结果 print(d) #3.14
4.比较大小
from decimal import Decimal # 创建两个Decimal对象 a = Decimal('0.1') b = Decimal('0.2') # 比较两个数的大小 if a < b: print("a < b") elif a == b: print("a = b") else: print("a > b") #a < b
5.转换类型
from decimal import Decimal # 创建一个Decimal对象 d = Decimal('3.14') # 转换为float类型 f = float(d) # 转换为int类型 i = int(d) # 输出结果 print(f, i) #3.14 3
6.格式化输出
from decimal import Decimal # 创建一个Decimal对象 d = Decimal('3.14159') # 将Decimal对象格式化为字符串,保留两位小数 s = '{:.2f}'.format(d) # 输出结果 print(s) #3.14
7.判断是否为正负无穷或NaN
from decimal import Decimal # 创建一个Decimal对象 d = Decimal('Infinity') # 判断是否为正无穷 if d.is_infinite() and d > 0: print("d is positive infinity") # 判断是否为负无穷 if d.is_infinite() and d < 0: print("d is negative infinity") # 判断是否为NaN if d.is_nan(): print("d is NaN") #d is positive infinity
8.小数转分数
from decimal import Decimal # 创建一个Decimal对象 d = Decimal('0.6666666666666666666666666667') # 转换为分数 f = d.as_integer_ratio() # 输出结果 print(f) #(2, 3)
9.转科学计数法
from decimal import Decimal # 创建一个Decimal对象 d = Decimal('123456789') # 转换为科学计数法 s = d.to_eng_string() # 输出结果 print(s) #1.23456789E+8