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!

3 Answers

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

This was very helpful, thank you!

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.

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());

You could write your own function to do it correctly:

function writeVectorProperly ( theV : Vector3 ) 
{
    return "(" + theV.x + ", " + theV.y + ", " + theV.z + ")"; 
}