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();
The round( ) function in the C programming language provides the integer value that is nearest to the float, the double or long double type argument passed to it. If the decimal number is between “1 and. 5′′, it gives an integer number less than the argument. If the decimal number is between “.
Float is a datatype which is used to represent the floating point numbers. It is a 32-bit IEEE 754 single precision floating point number ( 1-bit for the sign, 8-bit for exponent, 23*-bit for the value. It has 6 decimal digits of precision.
For example, 5.48958123 should be printed as 5.4895 if given precision is 4. In C, there is a format specifier in C. To print 4 digits after dot, we can use 0.4f in printf(). Below is program to demonstrate the same.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With