c# - MidpointRounding.ToZero 在 Unity 中不起作用

标签 c# unity3d

我需要使用不同于默认“四舍五入”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#。通过电子邮件发送 byte[] 然后检索它

c# - 在 C# 中使用多线程加速循环(问题)

c# - A* 多网格寻路

c# - Unity中启用、isActiveAndEnabled和activeInHierarchy的区别

c# - 如何在unity inspector中制作折线图

c# - SceneManager 不存在 Unity 命名空间错误

c# - 以编程方式在 WPF 中移动 TextBlock

c# - 有时我的 listBox1 或我在里面更新的值会闪烁一秒或更短时间,我该如何解决?

c# - 使用 "where"将模板限制为非 bool 结构类型

c# - 团结 |按指定角度(0~360度)旋转游戏对象