python报错TypeError: unsupported operand type(s) for -: ‘decimal.Decimal‘ and ‘float‘的解决方法

问题描述

在编写python代码时,进行小数位相减时出现 TypeError: unsupported operand type(s) for -: ‘decimal.Decimal’ and ‘float’ 的错误提示信息

在这里插入图片描述

原因分析

以上导致报错的原因是,双精度类型和浮点型相减报错

Python 内置类浮点数执行计算时,我们会惊奇发现计算结果与我们想象的完全不一样,比如我们都知道1.1和2.2的总和是3.3,但在Python中却不是这样的。

>>> (1.1 + 2.2) == 3.3
False
>>> 1.1 + 2.2
3.3000000000000003
>>>

解决方法

为了解决这个问题,我们可以使用Python附带的十进制模块。浮点数的精度最多为 15 位小数,而小数点数模块的精度可由用户设置。

from decimal import Decimal

print(0.1)
print(decimal.Decimal(0.1))

输出结果

>>> from decimal import Decimal
>>> print(0.1)
0.1
>>> print(Decimal(0.1))
0.1000000000000000055511151231257827021181583404541015625
>>>

修改python代码,如下所示:

# yx_jxxs = (jxxs - 1.1) / (0.15 * 12)  // TypeError: unsupported operand type(s) for -: 'decimal.Decimal' and 'float'
yx_jxxs = (jxxs - Decimal("1.1")) / Decimal(str(0.15*12))

运行代码,错误解决

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cdtaogang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值