Wednesday, November 15, 2017

Distances to human readable text in C#


Needed a function that converts a double to a human readable distance in my latest project, ended up writing the following function.
Input argument is in meters.
For values less than 1 meter, the result is given as centimeters.
For values up to 10 km, the values are given with one decimal.
Values up to one tenth of an Astronomical Unit are given as kilometers.
Values between one tenth of an Astronomical Unit and one tenth of a Parsec are given in Astronimical Units.
Values larger then one tenth of a Parsec are given in Parsecs.

Example output
Input
Output
0.533
53 cm
-1 -1 m
1 1 m
3,08568E+16 1.0 pc
3,08568E+17 10.0 pc
1,49598E+12 10.0 AU
1000 1.0 km
10000 10 km


The code for you to use as you please:
public const double AstronomicalUnit = 149597870700;
// https://en.wikipedia.org/wiki/Parsec
public static double Parsec { get; } = (648000 / Math.PI) * AstronomicalUnit;
public static string ToReadableDistanceFavorParsec(double meters, CultureInfo cultureInfo = null)
{
    if (cultureInfo == null)
        cultureInfo = CultureInfo.InvariantCulture;
    var sign = meters.Sign() > 0 ? string.Empty : "-";
    meters = meters.Abs();
    if (meters > (Parsec / 10))
    {
        return $"{sign}{(meters / Parsec).ToString("0.0", cultureInfo)} pc";
    }

    if (meters > (AstronomicalUnit / 10))
    {
        return $"{sign}{(meters / AstronomicalUnit).ToString("0.0", cultureInfo)} AU";
    }

    if (meters > (997))
    {

        if (meters >= (10000))
        {
            return $"{sign}{(meters / 1000).ToString("0", cultureInfo)} km";
        }
        return $"{sign}{(meters / 1000).ToString("0.0", cultureInfo)} km";
    }

    if (meters < 1)
    {
        return $"{sign}{meters * 100:0} cm";
    }
    return sign + meters.ToString("0") + " m";
}


All code provided as-is. This is copied from my own code-base, May need some additional programming to work. Use for whatever you want, how you want! If you find this helpful, please leave a comment, not required but appreciated! :)

Hope this helps someone out there!