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

本文关键字:小数点 舍入 | 更新日期: 2023-09-27 18:33:14

我想将我的答案四舍五入到小数点后一位。 例如: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();

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

你被除以一个int,结果会给出一个int(这使得 13/7 = 1)

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

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

averagesDoubles = Math.Round(averagesDoubles, 2);负责舍入双精度值。它将舍入,5.976 5.98,但这不会影响值的表示。

ToString()负责小数的表示。

尝试:

averagesDoubles.ToString("0.0");

根据 Math.Round 的定义,验证averagesDoubles是双精度还是十进制,并将这两行组合在一起:

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

自:

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

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

int 除法将始终忽略分数

 (sumInt / ratingListBox.Items.Count); 

这里 sumint 是 int 和 ratingListBox.Items.Count 也是 int,所以除法永远不会产生分数

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

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