python float 精度 处理

way1:Decimal

示例代码:

from decimal import Decimal
numStr = '1.13'
print('====a', Decimal(numStr) * Decimal('1e8'))
print('====b', Decimal(numStr) * Decimal(1e8))
print('====c', Decimal(float(numStr)) * Decimal('1e8'))
print('====d', Decimal(float(numStr)) * Decimal(1e8))

输出结果:

示例代码输出结果:
====a 1.13E+8
====b 113000000.00
====c 112999999.9999999893418589636
====d 112999999.9999999893418589636

示例1说明: numStr 1.13 × 1e8期望值是113000000.00,而实际计算过程中因为float精度问题会导致计算结果出现偏差。具体原因可以看文末的参考。示例1是使用Decimal计算的结果对比,可以看出如果要得出期望值时,可以考虑使用b输出结果的计算方式。

way2:round

示例代码:

numStr = '1.13'
a = float(numStr)*1e8
print('====a', a)
print('====b',round(a))
print('====c', round(a,2))
print('====d', round(a,3))
print('====e', '%.3f'%a)

输出结果:

示例代码输出结果:
====a 112999999.99999999
====b 113000000
====c 113000000.0
====d 113000000.0
====e 113000000.000

示例2说明: 示例2是使用round() 方法返回浮点数a的四舍五入值。也可以得到期望值113000000.0,如果需要对计算结果进行小数点保留可以使用e输出结果的方式。

参考:
1、

Python之☞float浮点数精度问题 - String-Lee - 博客园 (cnblogs.com)https://www.cnblogs.com/String-Lee/p/9840160.html
2、Asking for Help/How can I add or substract two to the last digit of a float? - Python Wikihttps://wiki.python.org/moin/Asking%20for%20Help/How%20can%20I%20add%20or%20substract%20two%20to%20the%20last%20digit%20of%20a%20float%3F?highlight=%28%5CbCategoryAskingForHelpAnswered%5Cb%29
3、
11. Brief Tour of the Standard Library — Part II — Python 3.10.4 documentationhttps://docs.python.org/3/tutorial/stdlib2.html#decimal-floating-point-arithmetic
4、Python3.中的浮点数运算(存在的.99999问题)_小白羊000的博客-CSDN博客https://blog.csdn.net/qq_41447652/article/details/123953908?utm_medium=distribute.pc_relevant.none-task-blog-2~default~baidujs_title~default-1.pc_relevant_paycolumn_v3&spm=1001.2101.3001.4242.2&utm_relevant_index=4%E2%80%8B

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值