简体   繁体   English

在 c++ 中处理金钱输入的最佳方式是什么?

[英]Best way to handle handle input for money in c++?

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.所以我在 c++ 中制作了一个基本的银行程序,并有一笔存款 function 接受双精度,所以我想处理来自用户的双精度输入,该双精度作为货币有效,因此到小数点后 2 位且不少于 0。

What is the best way to go about this? go 关于这个的最佳方法是什么? 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;
            }

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.1

0.0001100110011001100110011001100110011001100110011...

This is an example how 0.1 is stored in a float.这是一个如何将 0.1 存储在浮点数中的示例。 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:这是由于删除了...11001100...的无限小数位造成的,因为我们无法存储它们的所有(无限个):

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.每次需要时, recalculate() function 会将整数转换为“人类如何阅读它”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM