In one part of my code I convert from decimal coordinates to degrees/minutes/seconds and I use this:
double coord = 59.345235;
int sec = (int)Math.Round(coor
For those who prefer regular expression and to handle format like DDMMSS.ffffdS This function could easily be updated to handle other format.
C#
Regex reg = new Regex(@"^((?\d{1,2}(\.\d+)?)(?[SN])|(?\d{2})(?\d{2}(\.\d+)?)(?[SN])|(?\d{2})(?\d{2})(?\d{2}(\.\d+)?)(?[SN])|(?\d{1,3}(\.\d+)?)(?[WE])|(?\d{3})(?\d{2}(\.\d+)?)(?[WE])|(?\d{3})(?\d{2})(?\d{2}(\.\d+)?)(?[WE]))$");
private double DMS2Decimal(string dms)
{
double result = double.NaN;
var match = reg.Match(dms);
if (match.Success)
{
var degrees = double.Parse("0" + match.Groups["D"]);
var minutes = double.Parse("0" + match.Groups["M"]);
var seconds = double.Parse("0" + match.Groups["S"]);
var direction = match.Groups["W"].ToString();
var dec = (Math.Abs(degrees) + minutes / 60d + seconds / 3600d) * (direction == "S" || direction == "W" ? -1 : 1);
var absDec = Math.Abs(dec);
if ((((direction == "W" || direction == "E") && degrees <= 180 & absDec <= 180) || (degrees <= 90 && absDec <= 90)) && minutes < 60 && seconds < 60)
{
result = dec;
}
}
return result;
}