- Home /
Vector3.ToString
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!
Answer by Wolfram · Dec 19, 2011 at 12:33 PM
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#.
Then click the little "thumbs up" button to indicate the answer was helpful. That helps others to find it.
I left a comment since I do not have upvoting privileges! Unity's implementation of the stack exchange system is not very friendly to us newcomers...
I see. That's unfortunate. I've sadly moved on from my Unity project, but still get emails sometimes. I read this answer and was shocked it had never been upvoted. Now I now why.
I am surprised nobody suggested this, but the best option for @AntLewis is actually ToString("R")
R means "Round Trip" which is designed to ensure that the value later read from the string is the same as when it was serialized.
@GRobecchi : Interesting. However, note this suggestion in the .net docs: Note: Recommended for the BigInteger type only. For Double types, use "G17"; for Single types, use "G9".
Answer by Tabemasu Games · Dec 17, 2014 at 01:58 PM
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());
Answer by jahroy · Sep 17, 2011 at 07:31 PM
You could write your own function to do it correctly:
function writeVectorProperly ( theV : Vector3 )
{
return "(" + theV.x + ", " + theV.y + ", " + theV.z + ")";
}
Your answer
Follow this Question
Related Questions
Rounding a position against the surface of an object. 1 Answer
How precise is unity with it´s transforms? 2 Answers
Getting the same 'rounded' value of a Vector3? 3 Answers
How to calculate a Vector3 point having three given Vector3 points and an angle of 90 degrees? 1 Answer
help with vector3 2 Answers