- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我需要使用不同于默认“四舍五入”Mathf.Round()
的中点舍入规则。 Mathf.Round()
没有中点舍入参数,所以我使用 System.Math.Round()
。
C# 有不同的中点舍入策略,在此处指定:https://learn.microsoft.com/en-us/dotnet/api/system.midpointrounding?view=net-6.0 . MidpointRounding.AwayFromZero
和(显然)MidpointRounding.ToEven
在 Unity 中工作,但由于某些原因,其他的 MidpointRounding.ToZero
不工作(“CS0117:‘MidpointRounding’不包含‘ToZero’的定义”)。
float firstN = ...
float lastN = ...
int begin = (int)Math.Round(firstN, MidpointRounding.AwayFromZero); //works
int end = (int)Math.Round(lastN, MidpointRounding.ToZero); //doesn't work
我绝对需要使用 MidpointRounding.ToZero
,确实没有其他选择。我将不得不再次重写大部分代码。编写我自己的舍入函数只是为了解决这个问题听起来也不好玩。
最佳答案
MidpointRounding.ToZero
,尽管被添加到 MidpointRounding
枚举中,但也不会执行您希望它执行的操作。它只是截断数字的小数部分,为您提供离零不远的最接近的整数:
2.4 ==> 2
2.5 ==> 2
2.6 ==> 2
-2.4 ==> -2
-2.5 ==> -2
-2.6 ==> -2
很遗憾,看起来您需要自定义舍入方法,但这并不困难:
int i = (d < 0) ? (int)Math.Floor(d+0.5) : (int)Math.Ceiling(d-0.5);
结果:
2.4 ==> 2
2.5 ==> 2
2.6 ==> 3
-2.4 ==> -2
-2.5 ==> -2
-2.6 ==> -3
关于c# - MidpointRounding.ToZero 在 Unity 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71117861/
在C#中,MidpointRounding.ToEven和MidpointRounding.AwayFromZero这两种小数舍入策略在精度上有区别吗?我的意思是两者都确保在四舍五入的数字之间均匀分布
我遇到了一个相当烦人的问题。 假设我有小数 2.5,我希望它四舍五入。我的所有研究都告诉我: Math.Round(2.5, 0, MidpointRounding.AwayFromZero) 会给我
我正在做一个应用程序,我需要始终使用 MidpointRounding.AwayFromZero 对数字进行四舍五入,但每次进行四舍五入时,我都必须编写以下语句 Math.Round(xxx, ddd
我需要使用不同于默认“四舍五入”Mathf.Round() 的中点舍入规则。 Mathf.Round() 没有中点舍入参数,所以我使用 System.Math.Round()。 C# 有不同的中点舍入
我需要使用不同于默认“四舍五入”Mathf.Round() 的中点舍入规则。 Mathf.Round() 没有中点舍入参数,所以我使用 System.Math.Round()。 C# 有不同的中点舍入
这个问题在这里已经有了答案: Why does .NET use banker's rounding as default? (5 个答案) 关闭 9 年前。 以下适用: var rounded =
在 .NET 中,为什么 System.Math.Round(1.035, 2, MidpointRounding.AwayFromZero) 产生 1.03 而不是 1.04?我觉得我的问题的答案在
我想从 c# 中的这一行在 javascript 中获得相同的结果: round = Math.Round((17245.22 / 100), 2, MidpointRounding.AwayFrom
为什么这会导致 0 而不是 1? Math.Round(0.5, 0, MidpointRounding.AwayFromZero) 这是一个例子:http://ideone.com/ayMVO 最佳
我使用的是 Visual Studio Professional 2012。我创建了一个新的 C# ConsoleApplication,目标是 .NET Framework 4.5,代码如下:
在 .NET 中,为什么 System.Math.Round(27.2351, 2, MidpointRounding.AwayFromZero) 产生 27.24 而不是 27.23? 第三个数字是
我有一个 Math.Round 的错误,没有任何解释。当我做 Math.Round(81.725, 2, MidpointRounding.AwayFromZero) 结果是 81,72 但是当我用
我如何在 Delphi 中使用类似 Math.Round 和 MidpointRounding.AwayFromZero 的 c#? 等同于: double d = 2.125; Console.Wr
我是一名优秀的程序员,十分优秀!