private void txtFinal_Leave_1(object sender, EventArgs e)
{
int prelim;
int midterm;
int final;
decimal average;
string remarks;
prelim = int.Parse(txtPrelim.Text);
midterm = int.Parse(txtMidterm.Text);
final = int.Parse(txtFinal.Text);
average = (prelim + midterm + final) / 3;
txtAverage.Text = average.ToString();
if (average >= 75)
{
remarks = "passed";
}
else
{
remarks = "failed";
}
txtRemarks.Text = remarks;
// this is the output 83 passed
// I want to be like this 83.25 passed
}
Asked
Active
Viewed 97 times
0

Pero P.
- 25,813
- 9
- 61
- 85

Rob Manuel
- 15
- 2
-
2you can't get decimals with integers – RadioSpace Nov 26 '14 at 23:35
-
1try `/ 3M` instead of `/ 3` – Matthew Strawbridge Nov 26 '14 at 23:37
-
1Should be duplicate. Are you really sure no one hit this issue before? Maybe http://stackoverflow.com/questions/10851273/why-integer-division-in-c-sharp-returns-an-integer-but-not-a-float helps? – Alexei Levenkov Nov 27 '14 at 00:12
2 Answers
1
average = (prelim + midterm + final) / 3.0m;
This will fix your problem.
Int is an integer type; dividing two ints performs an integer division, i.e. the fractional part is truncated since it can't be stored in the result type (also int!). Decimal, by contrast, has got a fractional part. By invoking Decimal.Divide, your int arguments get implicitly converted to Decimals.
You can enforce non-integer division on int arguments by explicitly casting at least one of the arguments to a floating-point type, e.g.: 3.0m this is casting to decimal !

mybirthname
- 17,949
- 3
- 31
- 55
-2
please upgrade your code as follow:
average = Convert.ToDecimal(prelim + midterm + final) / 3;
txtAverage.Text = string.Format("{0:0.00}", average);

ymz
- 6,602
- 1
- 20
- 39