rawan
rawan

Reputation: 29

when trying to calculate discount price return 0 which is wrong c# Asp.net

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))); 
 }

Upvotes: 2

Views: 419

Answers (2)

Harsha KN
Harsha KN

Reputation: 93

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

Upvotes: 0

Heinzi
Heinzi

Reputation: 172230

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

Upvotes: 11

Related Questions