C#四舍五入到小数点后一位
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19090125/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Round to 1 decimal place in C#
提问by Pé Bin
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
我想将我的答案四舍五入到小数点后一位。例如:6.7、7.3 等。但是当我使用 Math.round 时,答案总是没有小数位。例如: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();
采纳答案by Jeroen van Langen
You're dividing by an int
, it wil give an int
as result. (which makes 13 / 7 = 1)
你除以一个int
,它会给出一个int
结果。(这使得 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.
该averagesDoubles = Math.Round(averagesDoubles, 2);
是承担一切四舍五入的双重价值。它将舍入5.976
到5.98
,但这不会影响值的呈现。
The ToString()
is responsible for the presentation of decimals.
该ToString()
负责小数的表现。
Try :
尝试 :
averagesDoubles.ToString("0.0");
回答by Vandesh
Do verify that averagesDoubles
is either double or decimal as per the definition of Math.Roundand combine these two lines :
averagesDoubles
按照Math.Round的定义验证它是双精度还是十进制,并结合这两行:
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.
上述情况中的 2 表示要四舍五入的小数位数。查看上面的链接以获取更多参考。
回答by TalentTuner
int division will always ignore fraction
int 除法将始终忽略分数
(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 ,所以除法永远不会导致分数
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 和 count 转换为 float 和 double 然后使用除法
回答by Narendra Singh
var val= Math.Ceiling(100.10m); result 101
var val= Math.Ceiling(100.10m); 结果 101