Question

I have List<myType> bound to DataTemplate with properties:

public int pID { get; set; }
public string NamePar { get; set; }
public decimal Count { get; set; }

Also textbox, where user can put decimal number or read it from weight. Im looking for solution to split entered decimal for product count, for example:

TextBox get 16.700 value from weight, productCount = 3, split is:

[1] 5.56

[2] 5.56

[3] 5.58

Another example 91/3

[1] 30.3

[2] 30.3

[3] 30.4

etc.

Any idea how I can solve this issue?

Was it helpful?

Solution

You can compute the result by checking if the item is the last one in the list, or if it's one of the initial N-1 items.

  • When it is one of the initial N-1 items, use Math.Truncate(100*Weight/Count)/100
  • When it is the last item, use Weight - ((Count-1) * Math.Truncate(100*Weight/Count) / 100)

The logic behind this is simple: when it's one of the initial numbers, truncate the result of division; compute the last number by subtracting the sum of truncated values from the total weight.

This approach produces two numbers after the decimal point, so your second example would looks like

30.33
30.33
30.34

OTHER TIPS

Just put the remainder on the last item:

public List<decimal> Allocate(decimal input, int items, int precision)
{
   decimal scale = (decimal)Math.Pow(10,precision);
   decimal split = Math.Truncate((input / items)*scale) / scale;
   List<decimal> output = Enumerable.Repeat(split, items).ToList();

   decimal remainder = input - output.Sum();
   output[output.Count - 1] += remainder;

   return output;
}

Although rounding seems like a more accurate method - you could build up a lot of truncation error if you have several items:

public List<decimal> Allocate(decimal input, int items, int precision)
{
   decimal split = Math.Round((input / items), precision);
   List<decimal> output = Enumerable.Repeat(split, items).ToList();

   decimal remainder = input - output.Sum();
   output[output.Count - 1] += remainder;

   return output;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top