在python中四舍五入浮点数



我有一个浮点数

a = 1.263597

我希望得到

b = 1.2635

但当我尝试

轮(,4)

则结果为

1.2636

我该怎么办?

用这个小修改试试math.floor

import math
def floor_rounded(n,d):
return math.floor(n*10**d)/10**d
n = 1.263597
d = 4
output = floor_rounded(n,d)
print(output)
1.2635

对于你的例子,你可以只做math.floor(1.263597 * 10000)/10000


编辑:根据@Mark的有效注释,这里有另一种解决此问题的方法,但这次使用字符串操作强制自定义舍入。

#EDIT: Alternate approach, based on the comment by Mark Dickinson
def string_rounded(n,d):
i,j = str(n).split('.')
return float(i+'.'+j[:d])
n = 8.04
d = 2
output = string_rounded(n,d)
output
8.04

不导入任何库(甚至不是标准库)的普通Python:

def round_down(number, ndigits=None):
if ndigits is None or ndigits == 0:
# Return an integer if ndigits is 0
return int(number)
else:
return int(number * 10**ndigits) / 10**ndigits
a = 1.263597
b = round_down(a, 4)
print(b)
1.2635

注意这个函数向零舍入,也就是说,它将正浮点数舍入,并将负浮点数舍入。

def round_down(number, ndigits=0):
return round(number-0.5/pow(10, ndigits), ndigits)

运行:

round_down(1.263597, 4)
>> 1.2635

相关内容

最新更新