简体   繁体   中英

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

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.

int division will always ignore fraction

 (sumInt / ratingListBox.Items.Count); 

here sunint is int and ratingListBox.Items.Coun 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

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM