更新答案:
正如@jpm 在 cmets 中指出的那样,我原来的答案的问题是边界处的行为。 Python 3 使这变得更加困难,因为它使用“银行家”四舍五入而不是“老派”四舍五入。然而,在研究这个问题时,我发现了一个使用 decimal 库的更好的解决方案。
import decimal
def round_up(x, place=0):
context = decimal.getcontext()
# get the original setting so we can put it back when we're done
original_rounding = context.rounding
# change context to act like ceil()
context.rounding = decimal.ROUND_CEILING
rounded = round(decimal.Decimal(str(x)), place)
context.rounding = original_rounding
return float(rounded)
或者如果你真的只想要一个单线:
import decimal
decimal.getcontext().rounding = decimal.ROUND_CEILING
# here's the one-liner
float(round(decimal.Decimal(str(0.1111)), ndigits=2))
>> 0.12
# Note: this only affects the rounding of `Decimal`
round(0.1111, ndigits=2)
>> 0.11
这里有一些例子:
round_up(0.022499999999999999, 2)
>> 0.03
round_up(0.1111111111111000, 2)
>> 0.12
round_up(0.1111111111111000, 3)
>> 0.112
round_up(3.4)
>> 4.0
# @jpm - boundaries do what we want
round_up(0.1, 2)
>> 0.1
round_up(1.1, 2)
>> 1.1
# Note: this still rounds toward `inf`, not "away from zero"
round_up(2.049, 2)
>> 2.05
round_up(-2.0449, 2)
>> -2.04
我们也可以用它来四舍五入到小数点的左边:
round_up(11, -1)
>> 20
我们不乘以 10,从而避免in this answer 提到的溢出。
round_up(1.01e308, -307)
>> 1.1e+308
原始答案(不推荐):
这取决于您在考虑正数和负数时想要的行为,但是如果您想要总是四舍五入到更大的值(例如 2.0449 -> 2.05、-2.0449 -> -2.04),那么您可以这样做:
round(x + 0.005, 2)
或者更喜欢一点:
def round_up(x, place):
return round(x + 5 * 10**(-1 * (place + 1)), place)
这似乎也可以如下工作:
round(144, -1)
# 140
round_up(144, -1)
# 150
round_up(1e308, -307)
# 1.1e308