当前位置:
首页 > Python基础教程 >
-
Python decimal模块的使用示例详解
decimal 模块decimal意思为十进制,这个模块提供了十进制浮点运算支持,本篇文章主要给大家讲解Python decimal模块的使用,需要的朋友可以参考下
Python decimal 模块
Python中的浮点数默认精度是15位。
Decimal对象可以表示任意精度的浮点数。
getcontext函数
用于获取当前的context环境,可以设置精度、舍入模式等参数。
#在context中设置小数的精度
decimal.getcontext().prec = 100
通过字符串初始化Decimal类型的变量
因为通过浮点数初始化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函数
用于创建一个新的context环境,可以在该环境中设置精度、舍入模式等参数,不会影响全局的context环境。
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/129447436
栏目列表
最新更新
求1000阶乘的结果末尾有多少个0
详解MyBatis延迟加载是如何实现的
IDEA 控制台中文乱码4种解决方案
SpringBoot中版本兼容性处理的实现示例
Spring的IOC解决程序耦合的实现
详解Spring多数据源如何切换
Java报错:UnsupportedOperationException in Col
使用Spring Batch实现批处理任务的详细教程
java中怎么将多个音频文件拼接合成一个
SpringBoot整合ES多个精确值查询 terms功能实
SQL Server 中的数据类型隐式转换问题
SQL Server中T-SQL 数据类型转换详解
sqlserver 数据类型转换小实验
SQL Server数据类型转换方法
SQL Server 2017无法连接到服务器的问题解决
SQLServer地址搜索性能优化
Sql Server查询性能优化之不可小觑的书签查
SQL Server数据库的高性能优化经验总结
SQL SERVER性能优化综述(很好的总结,不要错
开启SQLSERVER数据库缓存依赖优化网站性能
uniapp/H5 获取手机桌面壁纸 (静态壁纸)
[前端] DNS解析与优化
为什么在js中需要添加addEventListener()?
JS模块化系统
js通过Object.defineProperty() 定义和控制对象
这是目前我见过最好的跨域解决方案!
减少回流与重绘
减少回流与重绘
如何使用KrpanoToolJS在浏览器切图
performance.now() 与 Date.now() 对比