Search code examples
c#percentage

How Get Discount-Percentage In C#


let suppose dis.text = 2, prc.text = 100, I am using these codes.It Should be net_prc.text = 98.But its giving me -100.Can anybody tell me why?,And how can i get correct discounted percentage??

 private void net_prcTabChanged(object sender, EventArgs e)
    {
        int d;
        int di;
        int i;
        d = Convert.ToInt32(dis.Text);
        i = Convert.ToInt32(prc.Text);
        di = -((d / 100) * i) + i;
        net_prc.Text = di.ToString();
    }

Solution

  • Your division, d / 100, is a division of integers, and it returns an integer, probably 0 (zero). This is certainly the case with your example d = 2.

    Addition: If you really want to do this with integers (rather than changing to decimal or double like many other answers recommend), consider changing the sub-expression

    ((d / 100) * i)
    

    into

    ((d * i) / 100)
    

    because it will give you a better precision to do the division as the last operation. With the numbers of your example, d=2 and i=100, the first sub-expression will give 0*100 or 0, while the changed sub-expression yields 200/100 which will be 2. However, you will not get rounding to nearest integer; instead you will get truncating (fractional part is discarded no matter if it's close to 1).