Can someone tell whats wrong with my code?
I've already tried casting first the value but I get the same result.
/// <summary>
/// Discount function
/// </summary>
/// <param name="ToDiscount">Price of an item</param>
/// <param name="Discount">Discount</param>
/// <param name="Type">Percent or Amount</param>
/// <returns></returns>
private decimal Discount(decimal ToDiscount, int Discount, DiscountType Type)
{
decimal temp = 0;
try
{
if (Type == DiscountType.Percent)
{
int d = Convert.ToInt32((Discount / 100) * ToDiscount);
decimal f = ToDiscount - d;
temp = f;
}
else if (Type == DiscountType.Currency)
{
decimal FinalDiscount = ToDiscount - Discount;
temp = FinalDiscount;
}
}
catch (Exception ex)
{
Functions.ShowError(ex);
}
return temp;
}
Example:
Discount(5000, 5, DiscountType.Percent);
//calculation: (5/100) * 5000 = 250
//discount: 5000 - 250 = 4750
but the with that function I've created I get result 5000. instead of 4750. I did break point on return temp; but when I hover this part int d = Convert.ToInt32((Discount / 100) * ToDiscount);
no answer or no result.
Discount / 100
is performing integer division, in which the result is 0.
Hence (Discount / 100) * ToDiscount
also is 0, resulting in nothing being subtracted from ToDiscount
.
I think that the best thing for you to do would be to change the type of Discount
to being a decimal
, which would solve all of your problems there.
The line:
int d = Convert.ToInt32((Discount / 100) * ToDiscount);
Does integer arithmetic, where Discount / 100
will be zero for any discount between zero and 99.
You need to apply the discount via decimal, or floating point:
int d = Convert.ToInt32((Discount / 100m) * ToDiscount);
As an aside, naming a variable Type
is probably going to cause a few readability headaches down the line.
When you make this: Convert.ToInt32((Discount / 100) * ToDiscount); you will have have 0 because:
Discount /100 = 0 (if discount is intm the result will be int)
you should do a calculation with double numbers
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.