35

I would like to round my answer 1 decimal place. for example: 6.7, 7.3, etc. But when I use Math.round, the answer always come up with no decimal places. For example: 6, 7

Here is the code that I used:

int [] nbOfNumber = new int[ratingListBox.Items.Count];
int sumInt = 0;
double averagesDoubles;

for (int g = 0; g < nbOfNumber.Length; g++)
{
    nbOfNumber[g] = int.Parse(ratingListBox.Items[g].Text);
}

for (int h = 0; h < nbOfNumber.Length; h++)
{
    sumInt += nbOfNumber[h];
}

averagesDoubles = (sumInt / ratingListBox.Items.Count);
averagesDoubles = Math.Round(averagesDoubles, 2);
averageRatingTextBox.Text = averagesDoubles.ToString();
ʇolɐǝz ǝɥʇ qoq
  • 717
  • 1
  • 15
  • 30
Pé Bin
  • 441
  • 2
  • 9
  • 14

4 Answers4

76

You're dividing by an int, it wil give an int as result. (which makes 13 / 7 = 1)

Try casting it to a floating point first:

averagesDoubles = (sumInt / (double)ratingListBox.Items.Count);

The averagesDoubles = Math.Round(averagesDoubles, 2); is reponsible for rounding the double value. It will round, 5.976 to 5.98, but this doesn't affect the presentation of the value.

The ToString() is responsible for the presentation of decimals.

Try :

averagesDoubles.ToString("0.0");
Jeroen van Langen
  • 21,446
  • 3
  • 42
  • 57
11

Do verify that averagesDoubles is either double or decimal as per the definition of Math.Round and combine these two lines :

averagesDoubles = (sumInt / ratingListBox.Items.Count);
averagesDoubles = Math.Round(averagesDoubles, 2);

TO :

averagesDoubles = Math.Round((sumInt / ratingListBox.Items.Count),2);

2 in the above case represents the number of decimals you want to round upto. Check the link above for more reference.

Vandesh
  • 6,368
  • 1
  • 26
  • 38
1

int division will always ignore fraction

 (sumInt / ratingListBox.Items.Count); 

here sumint is int and ratingListBox.Items.Count is also int , so divison never results in fraction

to get the value in fraction , you need to datatype like float and type cast the sumInt and count to float and double and then use divison

javram
  • 2,635
  • 1
  • 13
  • 18
TalentTuner
  • 17,262
  • 5
  • 38
  • 63
-2

var val= Math.Ceiling(100.10m); result 101