C# - Math.Round

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1520990/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 18:22:08  来源:igfitidea点击:

C# - Math.Round

c#rounding

提问by Villager

I am trying to understand how to round to the nearest tenths position with C#. For instance, I have a value that is of type double. This double is currently set to 10.75. However, I need to round and then truncate everything past the tenths position. In this case, I am seeking a value of 10.8. How do I round to the tenths position in C#?

我试图了解如何使用 C# 舍入到最近的十分之一位置。例如,我有一个 double 类型的值。该双精度值目前设置为 10.75。但是,我需要舍入然后截断十分之一位置之后的所有内容。在这种情况下,我寻求 10.8 的值。如何四舍五入到 C# 中的十分之一位置?

Thank you!

谢谢!

采纳答案by Roatin Marth

Math.Round(yourNumber, 1)

The second parameter is number of decimal places to round to. In your case you want 1 decimal place as an end result.

第二个参数是要四舍五入的小数位数。在您的情况下,您需要 1 个小数位作为最终结果。

回答by Noldorin

You simply need to use the overload of Math.Roundthat takes the decimalsparameter.

您只需要使用带参数的重载Math.Rounddecimals

Math.Round(10.75, 1) // returns 10.8

Just for comparison:

仅供对比:

Math.Round(10.75)    // returns 11
Math.Round(10.75, 0) // returns 11
Math.Round(10.75, 2) // returns 10.75

回答by Bill the Lizard

Do you really need to round it, or can you just format it for printing but allow the variable itself to hold its precision? Something like:

你真的需要四舍五入吗,或者你可以只格式化它以进行打印但允许变量本身保持其精度?就像是:

decimal value = 10.75;
value.ToString ("#.#");

回答by Joel Coehoorn

Since you Used Math.Round()in your title, I'm going to assume you've already tried the basic Math.Round(10.75,1)approach and it returns something you don't expect. With that in mind, I suggest looking at some of the different overloads for the function, specifically one that accepts a MidPointRoundingenum:

由于您Math.Round()在标题中使用了,我将假设您已经尝试了基本Math.Round(10.75,1)方法并且它返回了您不期望的东西。考虑到这一点,我建议查看该函数的一些不同重载,特别是接受MidPointRounding枚举的重载:

http://msdn.microsoft.com/en-us/library/f5898377.aspx

http://msdn.microsoft.com/en-us/library/f5898377.aspx

回答by Toto

If you just want to "cut" everything after the first decimal, this shoudl work :

如果您只想“剪切”第一个小数点后的所有内容,则应该这样做:

   return Math.Round(value * 10)/10