当前位置:网站首页>保留小数位数时,可能会出现不按四舍五入进位,简单的解决方案
保留小数位数时,可能会出现不按四舍五入进位,简单的解决方案
2022-07-15 16:39:00 【嘿嘿骑士】
在Python中运行如下代码:
a = 2.358755
print(a)
print(decimal.Decimal.from_float(a))
print('\n保留5位小数的结果:')
print(format(a, '.5f'))
运行结果:
2.358755
2.358754999999999935056393951526843011379241943359375
保留5位小数的结果:
2.35875
可以看到,结果不对。实际上,保留5位小数的结果是 2.35876
这是由于底层代码的原理造成的,看第2行的结果,2.358754999999999935056393951526843011379241943359375 ,第6位小数是4,所以得出2.35875
使用如下代码可以解决这个问题:
def format_float(data, n):
""" 给定数据,保留n位小数 例子: format(2.358755, '.5f') ,结果是 2.35875,正确四舍五入值是 2.35876 """
digit = len(str(data).split('.')[-1]) # 计算小数位数
if n == digit - 1: # 保留的位数正好比总的小数位数少一位,则在后面补1
data = float(str(data) + '1')
return format(data, f'.{n}f')
a = 2.358755
print(format_float(a, 5))
运行结果:
2.35876
实际上在原来的浮点数后面补1就可以解决这个问题,补1后的实际数据:
print(decimal.Decimal.from_float(2.3587551))
运行结果:
2.358755100000000215487716559437103569507598876953125
可以看到第6位的数据现在是5,所以能准确得到四舍五入的值。
边栏推荐
- Gurobi在PyCharm中的配置与应用
- 循环语句及数组
- R语言dplyr包summarise_all函数计算dataframe数据中所有数值数据列的均值和中位数、使用sapply筛选数值数据列(Summarize all Numeric Variables
- [C #] commonly used utils
- Functions and symbols
- leetcode:74. Search 2D matrix
- LeetCode 188. The best time to buy and sell stocks iv*** (double, need triple)
- The difference between let / const /var
- 論文中的好文佳句摘錄
- Matlab-mex
猜你喜欢

Gurobi——GRBLinExpr

医疗单据OCR识别+知识库校验,赋能保险智能理赔

Problems that enterprises need to pay attention to when creating product help centers!

Ffmpeg audio and video unpacking

【300+精选大厂面试题持续分享】大数据运维尖刀面试题专栏(四)

关于结构体,枚举,联合等自定义类型的笔记

虹科案例|nanoGUNE应用Onyx系统实现石墨烯电学性质的无损表征

软件研发效能需求价值流分析专题

不能不知道的分布式基础理论

Mysql database installation & Problems
随机推荐
数组模拟链表
R language ggplot2 visualization: use the ggstripchart function of ggpubr package to visualize the dot strip plot, set the position parameter to configure the separation of different grouped data poin
那些年我们用过的分布式锁,你都get到了吗
flink. 14. How is the underlying layer of datastream module source implemented?
软件研发效能需求价值流分析专题
Excerpts of good articles and sentences in the thesis
TCP 三次握手、四次挥手图解
【C#】常用的Utils
Function advanced application
[Mori city] random talk on GIS data (IV) - coordinate system
Symbol data type
领域驱动设计基础
Explanation of smart factory terms
leetcode:330. 按要求补齐数组
设置dropout参数技巧
循环语句及数组
Huawei cloud stack opens its framework to the south to help ecological partners enter the cloud efficiently
C 基本语法解读: 总结程序中的一些常用到的但是容易混乱的函数(i++与++i) (位域)
看完这5个理由,我终于知道FTP被替代的原因
Extrait d'un bon article