Hi I’m using the ToString method to convert a Vector3 to a string so I can save it to a text file. Unfortunately, when I do, it rounds the vector3 members and only save them to one decimal place. So Vector3 ( 0.454502f, 0.9543028f, 31.54063f ) becomes Vector3(0.5f, 0.1f, 31.5f)
Is there anyway to prevent this rounding?
Thanks!
Wolfram
3
Yes, the default behaviour is very annoying, and makes handling small values such as normalized Vectors, or Colors useless.
However, you can call ToString() explicitly and apply a formatting parameters yourself:
-
For example, probably the most useful option (which I wished was default!) Vector3 ( 0.4f, 0.9543028f, 31.54063f ).ToString(“G4”) will show up to 4 significant digits for every component, and will show as:
(0.4, 0.9543, 31.54)
-
The variant Vector3 ( 0.4f, 0.9543028f, 31.54063f ).ToString(“F3”) will always show 3 digits after the decimal point for every component, but again for very small numbers you’ll lose precision. It will show as:
(0.400, 0.954, 31.541)
This works both in JavaScript and C#.
You can also write a Vector3 expansion, like this:
using UnityEngine;
public static class Vector3Extension {
public static string Print(this Vector3 v) {
return v.ToString("G4");
}
}
Then you have a new method available for your Vector3’s:
Vector3 v = new Vector3(0.0, 0.55421, 0.0);
UnityEngine.Debug.Log(v.Print());
jahroy
2
You could write your own function to do it correctly:
function writeVectorProperly ( theV : Vector3 )
{
return "(" + theV.x + ", " + theV.y + ", " + theV.z + ")";
}