Convert decimal coordinates to Degrees, Minutes &

2019-02-15 19:23发布

问题:

Has anyone know simple short code to convert this without use additional libraries ?

回答1:

Like this:

double coord = 59.345235;
int sec = (int)Math.Round(coord * 3600);
int deg = sec / 3600;
sec = Math.Abs(sec % 3600);
int min = sec / 60;
sec %= 60;

Edit: Added an Abs call so that it works for negative angles also.



回答2:

you could use timespan: (tricky but it works)

   double coord = 123.312312;   
   var ts = TimeSpan.FromHours(Math.Abs(coord))
   int degrees = Math.Sign(coord) * Math.Floor(ts.TotalHours);
   int minutes = ts.Minutes;
   int seconds = ts.Seconds;


回答3:

I am infering from your question that you want to convert from cartesian to polar coordinates.

If this is the case, the basic formulae you need are:

r = √ (x2 + y2)

θ = atan( y / x )

Where r is the distance and θ is the angle from x = 0 (about the origin)

Does this help?



回答4:

I came up with the following. It correctly handles negative coordinates (south latitude or west longitude) and returns the remainder (in degrees) that was not evely divided into minutes or seconds.

public static double ConvertDecimalToDegMinSec(double value, out int deg, out int min, out int sec)
{
    deg = (int)value;
    value = Math.Abs(value - deg);
    min = (int)(value * 60);
    value = value - (double)min / 60;
    sec = (int)(value * 3600);
    value = value - (double)sec / 3600;
    return value;
}