经度是分和秒是按60进位,如果要做运算第一步就是转换成浮点数,之后就是计算和还原。
using System.Text.RegularExpressions;
public static double DegreeFromString(string str)
{
Match match = Regex.Match(str,
@"(?<hour>[0-9]+)°(?<minute>[0-9]+)(′|')(?<second>[0-9]+(.[0-9]+)?)(″|""|'')");
if (match.Success)
{
double hour = 0, minute = 0, second = 0;
double.TryParse(match.Result("${hour}"), out hour);
double.TryParse(match.Result("${minute}"), out minute);
double.TryParse(match.Result("${second}"), out second);
return hour + minute / 60 + second / 3600;
}
else return 0;
}
public static string DegreeToString(double degree)
{
double minute = (degree - (int)degree) * 60;
double second = (minute - (int)minute) * 60;
return string.Format(
"{0:#}°{1:#}′{2:#.00}″",
degree,
Math.Abs(minute),
Math.Abs(second));
}
private void button1_Click(object sender, EventArgs e)
{
Console.WriteLine(DegreeToString(DegreeFromString("20°53'41''")));
Console.WriteLine(DegreeToString(DegreeFromString("10°11'20.5''")));
Console.WriteLine(
DegreeToString(DegreeFromString("20°53'41''") - DegreeFromString("10°11'20.5''")));
Console.WriteLine(
DegreeToString(DegreeFromString("10°11'20.5''") - DegreeFromString("20°53'41''")));
}
输出:
21°54′41.00″
10°11′20.50″
11°42′20.50″
-11°42′20.50″