Rounding Problem with Python [duplicate]

2020-04-16 04:08发布

Possible Duplicate:
Python rounding error with float numbers

I have a rounding Problem in Python. If i calculate

32.50 * 0.19 = 6.1749999999999998

But this should be 6.175. If i round 6.1749999999999998 with 2 decimal places it correctly shows 6.18. So i can live with that.

But if i calculate this:

32.50 * 0.19 * 3 = 18.524999999999999

This should be 18.525. If i round the value 18.524999999999999 with two decimal places it shows 18.52.

It should show me 18.53. What am i doing wrong and how can i fix it ?

7条回答
相关推荐>>
2楼-- · 2020-04-16 04:40

Use the Decimal Module from python to do accurate floating arithmatic

from decimal import Decimal, ROUND_UP

print (Decimal(32.50 * 0.19 * 3).quantize(Decimal('.01'), rounding=ROUND_UP))

Output: 18.53

查看更多
登录 后发表回答