1. 程式人生 > >unity3d中Debug.Log函式浮點精度問題

unity3d中Debug.Log函式浮點精度問題

經常用Debug.Log函式來列印程式中的變數值,發現它顯示的小數位數只有一位。
這個實在太低了,像0.0xxxxx這種小數就成了0.0!!!!!!
這誤差太大了也!
google了一下,確認是Debug.Log函式的問題,它在把Vector轉成字串的時候截斷了。
用下面的方法可以控制精度:

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

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).