Price division by 3

For an accounting program, I need to divide the price by 3 so that it can be divided within 3 months.

For example, 9 €

  • 3 € first month
  • 3 € second month
  • 3 € third month

Now it will be the price / 3

But what if the number is 10?

  • € 3.33 for the first month
  • € 3.33 second month
  • € 3.33 last month

€ 3.33 * 3 = € 9.99

One cent went missing. How can I make the output 3.33 €, 3.33 €, 3.34 €?

+6
math c # numbers
source share
4 answers

As Bathsheba said, first ask your users.

Here is a technique that I often used in such scenarios. This method will provide the most uniform distribution with an upward bias towards the end. For example, if you call DivvyUp(101, 3) , you will get 33.66, 33.67, 33.67 . Note that the distinction is not just made up at the end. Instead, each value is calculated according to what is left, and not what it started from.

 public static double[] DivvyUp(double total, uint count) { var parts = new double[count]; for (var i = 0; i < count; ++i) { var part = Math.Truncate((100d * total) / (count - i)) / 100d; parts[i] = part; total -= part; } return parts; } 
+5
source share

You need to ask the accountant what they would like here. This is important to do in software development: ask users.

Typically, for stability, you can deduct the amounts paid from the balance account and place the checks so that the balance remains zero.

And do not ever use a floating point data type when creating accounting software. Floating point accuracy will bite you. Use a currency type instead.

+15
source share

You can set the latter using the difference, instead of using the same calculation as the others. In pseudo code:

 normalMonthPrice = RoundToTwoPlaces(totalPrice / months); lastMonthPrice = totalPrice - (normalMonthPrice * (months - 1)); 
+11
source share

Congratulations, you’ve found out why the computer world isn’t as simple as “putting math on it” -

The simplest solution is to divide by 3, round to two decimal places and use this value for the first two months, and original - 2 * perMonth for the rest.

+3
source share

All Articles