这是我尝试过的:
>>> 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 显示以下 2 个链接:
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
您可以简单地去除最后一个字符:
pi = 3.14159
print(format(pi, '.5f')[:-1]) # 3.1415
我不确定您想要什么样的建议,但这里有一种方法可以将数字截断为给定的小数位数:
pi = 3.14159265
def truncate(v, places):
return int(v * 10**places) / 10**places
print(truncate(pi, 3)) # -> 3.141
print(truncate(pi, 4)) # -> 3.1415
试试这个。可能正好列出答案@U9-前进,有点紧凑。
>>> str(pi)[:6]
'3.1415'
希望这会有所帮助。
format(pi, '.4f')
有3.1416
,原因与format(pi, '.3f')
3.142
的原因相同 - 格式化输出中所需位数后的下一个数字至少为五 - 它被四舍五入。