Working With Floats and Integers

前端 未结 7 781
旧时难觅i
旧时难觅i 2020-12-21 08:40

I\'ve created an ATM like program which holds the money in a person\'s account. When the person takes out a withdrawal, it subtracts the withdrawal from the account along wi

7条回答
  •  爱一瞬间的悲伤
    2020-12-21 09:21

    You simply cannot use floating-point values to represent currency, since they have the wrong properties. Not all numbers are exactly representable, so you will have "mysterious" effects.

    It's better to use a "fixed-point" approach, the easiest is to take a largeish integer type such as long and then just multiplying it by an integer, typically 100 if all you need are whole cents (for US currency). If you need fractions of cents, multiply by more such as 10,000 to be able to represent all values down to 1/100:th of one cent.

    With this scheme, $1 would be:

    long one_dollar = 1 * 10000;
    

    And 13 cents would be:

    long thirteen_cents = 13 * 100;
    

    Note that this in turn limits how large amounts of money you can represent. Eventually, you may find you need an arbitrary-precision library to get "unlimited"-precision integers.

提交回复
热议问题