我想将我的答案舍入小数点后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();
Run Code Online (Sandbox Code Playgroud)
Jer*_*gen 50
你要除以a int,它会得到一个int结果.(这使得13/7 = 1)
首先尝试将其转换为浮点:
averagesDoubles = (sumInt / (double)ratingListBox.Items.Count);
Run Code Online (Sandbox Code Playgroud)
该averagesDoubles = Math.Round(averagesDoubles, 2);是承担一切四舍五入的双重价值.它将舍入5.976到5.98,但这不会影响值的表示.
该ToString()负责小数的表现.
试试:
averagesDoubles.ToString("0.0");
Run Code Online (Sandbox Code Playgroud)
averagesDoubles 根据Math.Round的定义验证是双精度还是十进制,并将这两行结合起来:
averagesDoubles = (sumInt / ratingListBox.Items.Count);
averagesDoubles = Math.Round(averagesDoubles, 2);
Run Code Online (Sandbox Code Playgroud)
至 :
averagesDoubles = Math.Round((sumInt / ratingListBox.Items.Count),2);
Run Code Online (Sandbox Code Playgroud)
上述情况中的2表示要向上舍入的小数位数.请查看上面的链接以获取更多参考.