Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help with a banking Program
#3
It's an issue caused by floating point arithmetic
look also at https://docs.python.org/3/tutorial/floatingpoint.html

>>> deposit = 1000.2
>>> withdrawal = 1000.1
>>> balance = deposit - withdrawal
>>> balance
0.10000000000002274
>>> print('{:.2f}'.format(balance))
0.10
>>> print(f'{balance:.2f}')
0.10
>>>
one way to deal with it (sufficient at least for homework purposes) is to use string formatting - f-strings or str.format() method so that you represent the result, being float, up to 2 decimal places precision

In real life, when dealing with number representing money amounts one would make sure to always work with correct precision, so that there is no artefacts like extra cent due to rounding accumulated over time. One way is to use decimal module

>>> from decimal import Decimal
>>> deposit = Decimal('1000.2')
>>> withdrawal = Decimal('1000.1')
>>> balance = deposit - withdrawal
>>> balance
Decimal('0.1')
>>> print(balance)
0.1
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Messages In This Thread
Help with a banking Program - by CrazyMakes - Jan-14-2020, 10:20 PM
RE: Help with a banking Program - by joe_momma - Jan-14-2020, 11:42 PM
RE: Help with a banking Program - by buran - Jan-15-2020, 07:11 AM
RE: Help with a banking Program - by perfringo - Jan-15-2020, 07:55 AM
RE: Help with a banking Program - by CrazyMakes - Jan-20-2020, 12:36 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020