I have checked dozens of other questions on stackoverflow about rounding floats in Python. I have learned a lot about how computers store these numbers, which is the root cause of the issue. However, I have not found a solution for my situation.
Imagine the following situation:
amount = 0.053
withdraw = 0.00547849
print(amount - withdraw)
>>> 0.047521509999999996
Here, I would actually like to receive 0.04752151, so a more rounded version. However, I do not know the number of decimals these numbers should be rounded upon.
So here it should have been okay with:
num_of_decimals = 8
round((amount - withdraw),num_of_decimals)
>>> 0.04752151
However, I do not know this parameter num_of_decimals. It could be 8,5,10,2,..
Any advice?
CodePudding user response:
When decimals are important, then Python offers a decimal
module that works best with correct rounding.
from decimal import Decimal
amount = Decimal(0.053)
withdraw = Decimal(0.00547849)
print(amount - withdraw)
# 0.04752150999999999857886789911
num_of_decimals = 8
print(round(amount - withdraw,num_of_decimals))
# 0.04752151
Instead of round
from decimal import getcontext
...
getcontext().prec = num_of_decimals
print(amount - withdraw)
# 0.047521510
See more decimal documentation
CodePudding user response:
Concentrating purely on the number of decimal places, something simple, like converting the number to a string might help.
>>> x = 0.00547849
>>> len(str(x).split('.')[1])
8
>>> x = 103.323
>>> len(str(x).split('.')[1])
3