python标准库(可在算法比赛使用的库)——decimal库

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值