So I'am making a basic banking program in c and have a deposit function that accepts a double, so i want to handle input from the user for a double that is valid as money so to 2 decimal places and not less than 0.
What is the best way to go about this? I have this so far, is there anything else I need to check for money validation or anything that can be done in less lines of code? thanks
// allow user to deposit funds into an account
try{
double amount = std::stoi(userInput); // userInput is a string
if (amount < 0)
{
throw std::invalid_argument("Amount cannot be negative");
}
// call function to deposit
std::cout << "You have deposited " << amount << " into your account." << std::endl;
}
catch(std::invalid_argument){
std::cout << "Invalid input." << std::endl;
}
CodePudding user response:
You should never use doubles or floats to store these types of information. The reason is that floats and doubles are not as accurate as they seem.
This is how 0.1 looks in binary:
>>> 0.1
0.0001100110011001100110011001100110011001100110011...
This is an example how 0.1 is stored in a float. It is caused by cutting out infinite number of decimal places of ...11001100..., because we are not able to store all (infinite number) of them:
0.1000000000000000055511151231257827021181583404541015625
So every float or double is not accurate at all. We can not see that at first sight (as the inaccuracy is really small - for some types of utilization), but the problem can accumulate - if we would do math operations with these numbers.
And a bank program is exactly the type of program, where it would cause problems.
I would propably create a structure:
struct Amount {
int dollars;
int cents;
void recalculate() {
dollars = cents / 100;
cents = cents % 100;
}
};
Where the recalculate() function would convert the integers to "how human would read it" every time you need it.