1

I have a small formula to apply to a money amount and i'm using cents (dividing the money about by 100) on my Money objects to make sure floats are not messing things up. However, i'm not sure how to apply a percentage calculation using that. For example, an interest rate formula of the following: $500 * 0,0048% * 5 (500 bucks, at 0,0048%/day, during 5 days)

How do i represent the percentage properly during my calculation? Would it have to be 50000 * 0.000048f * 5?

vinnylinux
  • 7,050
  • 13
  • 61
  • 127

2 Answers2

1

Technically you're supposed to calculate interest over interest, but let's ignore that for a moment.

Your interest rate is 48/1000000. Hence, the daily interest in cents is 50000 * 48/1000000. Floats are not needed, and in fact best avoided. They'd work in this case (small amount) but you'd soon need double.

MSalters
  • 173,980
  • 10
  • 155
  • 350
  • @vinnylinux: Because with the "magical constant" 10000000, the numerator would have been 480. You could also use 3/62500, but I believe that's less clear than 48/1000000 – MSalters Mar 21 '14 at 09:45
1

you need to evaluate your operations using fixed point arithmetics.

When you state that you are storing cents, you are in fact saying that your numbers have been all multiplied by 100 - that's another piece of information you are not storing. So 0.01$ is represented as 1/100. 0,0048 can be represented then as 48/10000 and the computation become:

50000/100 * 48/10000 * 5 = 12000000/1000000 = 1200/100

than you convert back to cents (IMPORTANT: at every step it's mandatory you check for overflows, missing bits) to normalize to your preferred representations

Note that this is also the typical approach used with micro-controllers (no fpu, low performance)

As an alternative, if you don't care much about performance you can also make use of arbitrary precision arithmetic libraries, as GMP.

Sigi
  • 4,826
  • 1
  • 19
  • 23
  • When using GMP, can i drop the usage of cents? – vinnylinux Mar 20 '14 at 13:14
  • yes: I used it only for arbitrarily long integers, but it has functions for rational numbers too, that are all you need in financial applications (I think). It has also a nice C++ interface: https://gmplib.org/manual/C_002b_002b-Interface-Rationals.html – Sigi Mar 20 '14 at 14:02