0

I'm writting a C++ program that takes user input and put it inside a file. In this case, it takes in a number (eg. 299.99), but C++ rounds it to 300 (used to be doubles) when using doubles and floats 299.9...

My code:

void Bank::deposit(){
std::cout << "You currently have " << getBalance() << " in your account.\nHow much would you like to deposit? Amount: ";
float amount = optionExists(amount);

if(amount < 1){
    std::cout << "Invalid Amount!" << std::endl;

    deposit();
}

float moneyInBank = getBalance();
setBalance(moneyInBank + amount);

std::cout << "Your balance of " << moneyInBank << " has been increased to " << getBalance() << std::endl;
std::string theLine = getUsername() + "," + getPassword() + "," + getAccountType() + "," + std::to_string(moneyInBank) + "," + std::to_string(getAdmin());
updateFile(theLine, getUsername(), getPassword(), getAccountType(), getBalance(), (getAdmin()));

displayMenu();
}

When I call the getBalance() method it also returns a float, but as I said, only to one decimal...

Here is a snippet from the text file:

[name,password,type,BALANCE,admin]

lisa,mag24@773,C,24.99,0  ---> What I want (manually entered)

lols,23456,L,30,1  ---> What I got when using doubles

mark,passw0rd,S,24509.9,1  ---> What I got when using floats

Extra Notes: I compile using cmake and code with VSCode

Geno C
  • 1,401
  • 3
  • 11
  • 26
Netsu
  • 17
  • 4
  • 1. `float` isn't suitable for most floating-point operations, use `double` instead. 2. Don't use binary floating-point types for monetary values – phuclv Aug 10 '20 at 16:43
  • See [this FAQ on floating-point numbers in C++](https://isocpp.org/wiki/faq/newbie#floating-pt-errs). What you probably want is a fixed-point number. Google for that, and I'm sure you'll turn up some Github hits. – metal Aug 10 '20 at 16:45
  • @phuclv floating-point types are not good for monetary operations to begin with. Inaccuracies and rounding cause loss of precision, which loses money. Better to use types that are designed specifically for monetary values, or at least convert floating-point values to fixed-precision integer values during calculations. – Remy Lebeau Aug 10 '20 at 16:46

1 Answers1

0

This link may help [link][1]

float iBalance = getBalance(); 

std::cout<< std::setprecision(2)<<iBalance<< endl; 

[1]: https://stackoverflow.com/questions/5907031/printing-the-correct-number-of-decimal-points-with-cout#:~:text=You%20have%20to%20set%20the%20'float%20mode'%20to%20fixed.&text=To%20set%20fixed%202%20digits,ios%3A%3Afixed)%3B%20cout.

Go Go Gadget 2
  • 148
  • 1
  • 2
  • 10