舍入 up/down 浮点数到 2 位小数
round up/down float to 2 decimals
我想用这些 input/output:
设计一个函数 f(x : float, up : bool)
# 2 decimals part rounded up (up = True)
f(142.452, True) = 142.46
f(142.449, True) = 142.45
# 2 decimals part rounded down (up = False)
f(142.452, False) = 142.45
f(142.449, False) = 142.44
现在,我知道 Python 的 round
内置函数,但它总是向上舍入 142.449
,这不是我想要的。
有没有比用 epsilons 进行一堆浮点数比较(容易出错)更好的 pythonic 方式来做到这一点的方法?
您是否考虑过使用 floor
和 ceil
的数学方法?
如果你总是想四舍五入到两位数,那么你可以将要四舍五入的数字预乘100,然后四舍五入到最接近的整数,然后再除以100。
from math import floor, ceil
def rounder(num, up=True):
digits = 2
mul = 10**digits
if up:
return ceil(num * mul)/mul
else:
return floor(num*mul)/mul
math.ceil()
向上舍入,math.floor()
向下舍入。因此,以下是如何使用它的示例:
import math
def f(x, b):
if b:
return (math.ceil(100*x) / 100)
else:
return (math.floor(100*x) / 100)
这个函数应该完全符合您的要求。
如果您不想使用任何显式函数,您也可以执行一些数学逻辑:
def f(num, up):
num = num * 100
if up and num != int(num): # if up and "float' value != 'int' value
num += 1
return int(num) / (100.0)
在这里,想法是如果 up
是 True
并且 int
值不等于 float
值然后将数字增加 1。否则它将与原来的数字相同
我想用这些 input/output:
设计一个函数f(x : float, up : bool)
# 2 decimals part rounded up (up = True)
f(142.452, True) = 142.46
f(142.449, True) = 142.45
# 2 decimals part rounded down (up = False)
f(142.452, False) = 142.45
f(142.449, False) = 142.44
现在,我知道 Python 的 round
内置函数,但它总是向上舍入 142.449
,这不是我想要的。
有没有比用 epsilons 进行一堆浮点数比较(容易出错)更好的 pythonic 方式来做到这一点的方法?
您是否考虑过使用 floor
和 ceil
的数学方法?
如果你总是想四舍五入到两位数,那么你可以将要四舍五入的数字预乘100,然后四舍五入到最接近的整数,然后再除以100。
from math import floor, ceil
def rounder(num, up=True):
digits = 2
mul = 10**digits
if up:
return ceil(num * mul)/mul
else:
return floor(num*mul)/mul
math.ceil()
向上舍入,math.floor()
向下舍入。因此,以下是如何使用它的示例:
import math
def f(x, b):
if b:
return (math.ceil(100*x) / 100)
else:
return (math.floor(100*x) / 100)
这个函数应该完全符合您的要求。
如果您不想使用任何显式函数,您也可以执行一些数学逻辑:
def f(num, up):
num = num * 100
if up and num != int(num): # if up and "float' value != 'int' value
num += 1
return int(num) / (100.0)
在这里,想法是如果 up
是 True
并且 int
值不等于 float
值然后将数字增加 1。否则它将与原来的数字相同