问题
I've read the following pages:
python decimals - rounding to nearest whole dollar (no cents) - with ROUND_HALF_UP
http://docs.python.org/library/decimal.html
I have the following code:
total_num = Decimal(str(total/10))
total_num.quantize(Decimal('1'), rounding=ROUND_UP)
But its always rounding down? So if I have 221, I want it to return 23. Right now I'm getting 22. Is there something I'm misunderstanding regarding this?
[EDIT]
I changed it to the following: total_num = int(math.ceil(float(total)/10))
I needed an int
to continue with the for
loop that has a range
.
回答1:
Can't you use math.ceil? It will do the necessary thing if you are using a float division. Currently you are doing an integer division.
回答2:
total
is an integer. As such, /
is doing integer division. Either divide by 10.
(and hope that precision limits don't bite you in the ***), or do your math in Decimal
with an appropriate context.
来源:https://stackoverflow.com/questions/11642387/rounding-up-with-python