-5

Hello guys/gals I need some help in my program that calculate the total numbers by dividing into three, first is 80% of total 2nd is 10% of total and thr last is 10% of total. I have tried it to convert to double but if the total is 5 the first one will output 4 and the 2nd is 0 and 3rd is 0 which is wrong because I am expecting the total of output as it is. Here is my code

    Double total = 5;
    Double a,b,c,tot;
    a = total*0.80;
    b = total*0.10;
    c = total*0.10;
   tot = a+b+c;
   Int convert = Convert.ToInt32(tot)
shampoo
  • 49
  • 3
  • 10
  • 1
    Please post what you have tried so far. – user3378165 Jul 04 '16 at 17:31
  • 3
    You should show what you have tried, it sounds like your dividing an integer by an integer – Sayse Jul 04 '16 at 17:32
  • 1
    First see [how to ask a question.](http://stackoverflow.com/help/how-to-ask) and then edit your question – Roman Marusyk Jul 04 '16 at 17:32
  • I do convert it to Double first to calculate total*0.80 for first and to output this on label i converted it to Int then to string. Which is good if the percentage is 60 40 20, which is when I convert double into int it automatically round it off. But not in 80 10 10. – shampoo Jul 04 '16 at 17:34
  • 1
    Please post your code. Your explanation makes things inexplicable. – Steve Jul 04 '16 at 17:38
  • I have already update my post – shampoo Jul 04 '16 at 17:40
  • ... Why do you convert it to an integer at the end?.. – Sayse Jul 04 '16 at 17:40
  • To round it off. Because it works when the percentage is 50% 30% and 20%. 5 gets 3,1,1. Which is basically 2.5 1.5 0.5. Btw i need it by whole number – shampoo Jul 04 '16 at 17:41
  • Int convert = tot gets error cannot explicit Int to doublr – shampoo Jul 04 '16 at 17:43
  • So if total is 5, a = 4, b = 0.5 and c=0.5 what do you expect b and c to be if you convert them to an int? – Steve Jul 04 '16 at 17:48
  • The one is will get 1 and another is 0. I need to produce it whole numbers in any of a,b,c – shampoo Jul 04 '16 at 17:49
  • Depending upon situation the sum of 4,0,0 is not the equal of total and if the total is 7 it provides 6,1,1 which is not the total of sum. The only correct on my situation is if the total is 10 which is 8,1,1 – shampoo Jul 04 '16 at 18:06

1 Answers1

0

This should work for you:

Int convert = Convert.ToInt32(tot + 0.5)

This way, tot will take the nearest integer. Knowing that 2.5 for example will be 3 and so on.

But you might need it to a, b and c like this:

tot = Convert.ToInt32(a + 0.5) + Convert.ToInt32(b + 0.5) + Convert.ToInt32(c + 0.5);

Khalil Khalaf
  • 9,259
  • 11
  • 62
  • 104