0

I am making a bank minigame, just messing with the code, nothing special. But for some reason, I am receiving some strange numbers. The amount is supposed to be 2 decimals like money works. But when I make the operation, I am receiving a big amount of numbers like 9's or 0's. It's better to show you actually. The minigame has few files. But I think these 2 are enough to understand the error.

money.py

bank_balance = 987.34
wallet_balance = 503.26

bank_deposit.py

import money

def bank_deposit():

    while True:
        try:
            deposit = float(input("Deposit: "))
            if deposit <= money.wallet_balance and deposit >= 0.01:
                print(f"Deposited ${deposit}!")
                break
            elif deposit == 0:
                print("You can't deposit $0!")
                continue
            else:
                print(f"You haven't got enough money in your pockets! You only have {money.wallet_balance}")
                continue
        except ValueError:
            print("Input must be a valid number!")


    money.bank_balance += deposit
    money.wallet_balance -= deposit

    print(f"Bank account balance: {money.bank_balance}")
    print(f"You have now ${money.wallet_balance} in your pockets.")

bank_deposit()

What I am receiving in the terminal it's this:

Deposit: 500
Deposited $500.0!
Bank account balance: 1487.3400000000001
You have now $3.259999999999991 in your pockets.

I don't understand why am I receiving this kind of number when the operation is supposed to be up to 2 decimals. I've been thinking about the round function, but I don't like that. I want to know the reason and fix it.

Thank you so much!

Lorak
  • 33
  • 6
  • 1
    It's best not to use floating point for numbers. Represent the amounts as integer numbers of pennies rather than dollars. – Barmar Mar 30 '23 at 15:24
  • So how may I solve this? – Lorak Mar 30 '23 at 15:31
  • 1
    Didn't I just tell you? Multiply everything by 100 and just deal with integers. When you want to display amounts, use `round(amount/100, 2)` – Barmar Mar 30 '23 at 15:36
  • Ok thank you. Sorry for the question. I didn't understand you the first time. – Lorak Mar 30 '23 at 15:56

0 Answers0