繁体   English   中英

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

[英]Round to 1 decimal place in C#

我想将我的答案舍入小数点后1位。 例如:6.7,7.3等。但是当我使用Math.round时,答案总是没有小数位。 例如:6,7

这是我使用的代码:

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

你用一个int除以它会得到一个int作为结果。 (这使得13/7 = 1)

首先尝试将其转换为浮点:

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

averagesDoubles = Math.Round(averagesDoubles, 2); 对于舍入双值是负责任的。 它会循环, 5.9765.98 ,但这不会影响值的表示。

ToString()负责小数的表示。

试试:

averagesDoubles.ToString("0.0");

根据Math.Round的定义,验证averagesDoubles是double还是decimal,并将这两行组合在一起:

averagesDoubles = (sumInt / ratingListBox.Items.Count);
averagesDoubles = Math.Round(averagesDoubles, 2);

至 :

averagesDoubles = Math.Round((sumInt / ratingListBox.Items.Count),2);

上述情况中的2表示要向上舍入的小数位数。 请查看上面的链接以获取更多参考。

int division将始终忽略分数

 (sumInt / ratingListBox.Items.Count); 

这里sunint是int,ratingListBox.Items.Coun也是int,所以divison永远不会产生分数

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

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

暂无
暂无

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

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