Round to 1 decimal place in C#

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

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.

Tags:

C#

Rounding