Skip to main content
 首页 » 编程设计

python之格式化 python 时小数会四舍五入

2025年05月04日11over140

这是我尝试过的:

>>> pi = 3.14159265 
>>> format(pi, '.3f') #print 3.142 # 3 precision after the decimal point 
'3.142' 
>>> format(pi, '.1f') #print 3.1 
'3.1' 
>>> format(pi, '.10f') #print 3.1415926500, more precision than the original 
'3.1415926500' 
>>> format(pi, '.5f') #print 3.14159, more precision than the original 
'3.14159' 
>>> format(pi, '.4f')  
'3.1416' 

关注的部分是这样的:

>>> format(pi, '.3f') #print 3.142 # 3 precision after the decimal point 
'3.142' 
>>> format(pi, '.4f')  
'3.1416' 

我期待的地方 3.1415 , 我得到 3.1416 .请给我建议。
SO 显示了这两个链接:
http://stackoverflow.com/questions/21895756/why-are-floating-point-numbers-inaccurate
http://stackoverflow.com/questions/1089018/why-cant-decimal-numbers-be-represented-exactly-in-binary
但这些不是我要找的。

请您参考如下方法:

因为它是round函数,所以它就像round函数一样。

修复它:

>>> l = str(pi).split('.') 
>>> l[0] + '.' + l[1][:4] 
'3.1415' 
>>> float(l[0] + '.' + l[1][:4]) 
3.1415 

它的函数版本:

def first_n(a, b): 
    l = str(a).split('.') 
    return int(l[0] + '.' + l[1][:b]) 

现在:

print(first_n(pi, 4)) 

给予:

3.1415