Pé Bin
Pé Bin

Reputation: 461

Round to 1 decimal place in C#

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

Upvotes: 37

Views: 127706

Answers (4)

TalentTuner
TalentTuner

Reputation: 17556

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

Upvotes: 1

Narendra Singh
Narendra Singh

Reputation: 1

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

Upvotes: -2

Jeroen van Langen
Jeroen van Langen

Reputation: 22038

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

Upvotes: 80

Vandesh
Vandesh

Reputation: 6894

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.

Upvotes: 13

Related Questions