2

When I'm trying to calculate a discount price, it returns 0 which is wrong. The total is 100 and the percentage discount is 10%. I am sure about this formula, but it's keep returning 0.

My c# code :

protected void TxtDiscountPER_TextChanged(object sender, EventArgs e)
{
     TxtDiscountAMT.Text = Convert.ToString(((Convert.ToInt16(TxtDiscountPER.Text)) / 100) * (Convert.ToInt16(TxtTotalAmt.Text))); 
 }
ceuben
  • 319
  • 1
  • 4
  • 17
rawan
  • 29
  • 8
  • 1
    What returns `Convert.ToInt16(TxtDiscountPER.Text)` exatly? Possible [integer divison](http://mathworld.wolfram.com/IntegerDivision.html) case. – Soner Gönül Apr 22 '15 at 12:28
  • Put a debugger in the event handler TxtDiscountPER_TextChanged and check the value in Text property of text boxes. I hope you will get a solution for your question. – Ankush Jain Apr 22 '15 at 12:41
  • Instead of 100, you could divide by 100.0 and get the result. A division by integer results in integer, and if the divisor is greater the result is obviously 0. You could get floating point result if you divide by 100.0. From which you can extract the result to correct decimal place. – Pramod Apr 22 '15 at 12:54
  • Reopened the question. The link to [Why integer division in c# returns an integer but not a float?](http://stackoverflow.com/q/10851273/87698) is helpful, but I do not think that it is a duplicate. In one case, "integer division" is the answer, in the other case, it is the question. – Heinzi Apr 23 '15 at 05:32

2 Answers2

11

Here:

(Convert.ToInt16(TxtDiscountPER.Text)) / 100

you divide an Int16 (10) by an Int32 (100) using integer division, yielding 0. To quote from MSDN:

When you divide two integers, the result is always an integer. For example, the result of 7 / 3 is 2. To determine the remainder of 7 / 3, use the remainder operator (%). To obtain a quotient as a rational number or fraction, give the dividend or divisor type float or type double.

I suggest that you use the decimal data type instead of float or double, since decimal is better suited for monetary values:

(Convert.ToDecimal(TxtDiscountPER.Text)) / 100
Heinzi
  • 167,459
  • 57
  • 363
  • 519
  • @rawan: Why? `10 / 100 = 0.1`. You cannot store `0.1` in an integer. If you want, your can convert your *result* back to an integer. If it's just about formatting, use the appropriate [format string](https://msdn.microsoft.com/en-us/library/dwhawy9k%28v=vs.110%29.aspx). – Heinzi Apr 23 '15 at 05:26
0

The division will return a decimal value. You are converting the division to Int16. So it will always return an INT value which is 0

Harsha KN
  • 93
  • 10