unity3d中Debug.Log函数浮点精度问题

来源:互联网 发布:android 监听网络变化 编辑:程序博客网 时间:2024/06/17 01:35

转自:http://blog.sina.com.cn/s/blog_5d76edd80101iwib.html


经常用Debug.Log函数来打印程序中的变量值,发现它显示的小数位数只有一位。
这个实在太低了,像0.0xxxxx这种小数就成了0.0!!!!!!
这误差太大了也!
google了一下,确认是Debug.Log函数的问题,它在把Vector转成字符串的时候截断了。
用下面的方法可以控制精度:

Debug.Log(vec.ToString("f4"))

参考这里:http://answers.unity3d.com/questions/173094/show-vector3-full-float-value.html

When you pass a vector to Debug.Log, I suspect Debug.Log calls the Vector’s ToString()-method for you, in order to make a string value out of the argument that it can write to the console. And the way Vector3.ToString() is implemented simply rounds the values to 1 decimal.

To get around this issue, you can either pass in the vector’s coordinates individually, or you can use the overload of ToString that accepts a format, to determine how many decimal points you want the vector represented in. You can use it like this, for example:

Vector3 point = new Vector3(0.9887f, 1.56789f, 3.09273475f);Debug.Log(point.ToString("F4"));

Here, the F means you’re talking about Fixed-point, and the 4 means you want 4 decimals. You can pass in any number instead of 4. See http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx for further information on what to pass to ToString(string format).

原创粉丝点击