python:浮点数精度

本文探讨了Python的Decimal类型在处理十进制精度问题时的行为,以及如何在Django的rest_framework中使用DecimalField设置最大位数和小数位数,包括coerce_to_string选项的应用。
摘要由CSDN通过智能技术生成

1. 十进制精度

from decimal import Decimal

a = 0.1 + 0.2  # 0.30000004
b = Decimal('0.2') + Decimal('0.1')  # Decimal('0.3')
c = b.quantize(Decimal('0.01'))  # 0.01为四舍五入保留2位小数,0.001为3位...

2. django支持

from rest_framework.serializers import ModelSerializer, Serializer

# max_digits整个数字长度10;decimal_places小数位数3,也就是整数位数10-3=7;
# coerce_to_string返回格式为字符串,默认True;
# 如果value=1.3那么coerce_to_string=False时返回1.3;
# coerce_to_string=True时返回"1.300"(3位小数)
b = serializers.DecimalField(max_digits=10, decimal_places=3, coerce_to_string=False)  

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值