简体   繁体   English

在C#中舍入到小数点后1位

[英]Round to 1 decimal place in C#

I would like to round my answer 1 decimal place. 我想将我的答案舍入小数点后1位。 for example: 6.7, 7.3, etc. But when I use Math.round, the answer always come up with no decimal places. 例如:6.7,7.3等。但是当我使用Math.round时,答案总是没有小数位。 For example: 6, 7 例如: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. 你用一个int除以它会得到一个int作为结果。 (which makes 13 / 7 = 1) (这使得13/7 = 1)

Try casting it to a floating point first: 首先尝试将其转换为浮点:

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

The averagesDoubles = Math.Round(averagesDoubles, 2); 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. 它会循环, 5.9765.98 ,但这不会影响值的表示。

The ToString() is responsible for the presentation of decimals. ToString()负责小数的表示。

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 : 根据Math.Round的定义,验证averagesDoubles是double还是decimal,并将这两行组合在一起:

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. 上述情况中的2表示要向上舍入的小数位数。 Check the link above for more reference. 请查看上面的链接以获取更多参考。

int division will always ignore fraction int division将始终忽略分数

 (sumInt / ratingListBox.Items.Count); 

here sunint is int and ratingListBox.Items.Coun is also int , so divison never results in fraction 这里sunint是int,ratingListBox.Items.Coun也是int,所以divison永远不会产生分数

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 要获得分数中的值,您需要像float这样的数据类型和类型转换sumInt并计数浮点数和双精度然后使用divison

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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