tags:

views:

102

answers:

4

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

+5  A: 

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.

Guffa
+2  A: 

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?

Ragster
+2  A: 

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;
Charles Bretana
Interresting, but it might be a bit confusing as it's not at all a time... And it doesn't work for negative angles...
Guffa
@Guffa, I agree! It's a `wtf??!!` fer sure.. but curious and illuminating as it illustrates (and capitalizes on ) the parallel between the two data structures. (fixed it to handle negatives)
Charles Bretana
+1  A: 

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;
}
Brian Gideon