将浮点数舍入为 -1、0 或 1

Round a float to -1, 0 or 1

我需要将浮点数舍入为 -1 或 1。如果浮点数等于 0,则将其保留为零。 现在我用这个:

Mathf.Clamp(x*1000000, -1f,1)

有没有更优雅的方案?

您可以使用 Math.Sign(x) 来做到这一点。当 x=0 时它将 return 0,如果 x 为负则为 -1,如果 x 为正则为 +1。我相信这会做你想要的。此处的文档:https://msdn.microsoft.com/en-us/library/z394hhsx(v=vs.110).aspx