Distance Changing Conversions (1000m = 1km 1200m = 1.2km etc)

Hello Unity.

I have myself a little radar system, which reads out distance from you to whoever is on it. No problem.

But, if you get farther than 1000 meters away, I run into issues with it fitting in my hud.
So I want to convert them up/down.

I currently just use Vector3.Distance a to b.
I did just multiply it, but I’m left with many many remaining places. Is there anyway to just get the first 1 or 2 digits after the decimal?

I would love for it to kick over and say 1.10km 1.76km

I suppose if this question is answered and problem solved. To save time asking another.
I would also like to know if there is an easy way to sort my GameObject List ascending based on said Distance. Closest to farthers top to bottom.

Huge thanks in Advance

Edit:

Screenshot of the radar element (I will be updating this to 4.6 UI later before anyone yells at me for using UnityGUI :wink: )

-Fatal

int distance = (int)Vector3.Distance(a,b);
string distanceText = null;
if(distance >= 1000)
{
float temp = (float)distance / 1000f;
distanceText = temp.ToString(“0.00”);
}else
{
distanceText = distance.ToString();
}
print(distanceText);

There may be better ways but this one is simple.

In regards to outputting the distance you could just use ToString() with a format specifier eg:

distance.ToString(“F2”);

This would display the string to 2 decimal places. You can do more with this also, depending on what you need. You could modify the float itself, but I think this is better because it is only for display purposes.

For ordering the list, I would look into something like Array.Sort as it is really quite fast, making sure you specify a comparison delegate that compares the distance property. Let me know if you need an example, I haven’t used it for a while, so it would take a little bit to knock one up. You can find the MSDN page for Array.Sort here:

Thanks to what Fafase said, I came up with this nifty pub string.

	public static string Distance(GameObject Player, GameObject target){
		float distance = Vector3.Distance(Player.transform.position, target.transform.position);
		string distanceText = null;
		if(distance >= 1000){
			float temp = (int)distance / 1000f;
			distanceText = temp.ToString("0.0" + "km");
		} else {
			distanceText = distance.ToString("0" + "m");
		}
		return distanceText;
	}

I will come up with a way to sort the radar list at another time, since I’ve moved on to shields for the next day or two. But awesome work thanks guys! Hope this helps anyone in the future.

I would imagine it wouldn’t be too difficult to step it up more past km, to AU or something.