rounding up with python

ε祈祈猫儿з 提交于 2019-12-11 06:51:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!