C#中double.TryParse解析坐标时丢失小数点问题及解决方法
问题描述
执行double.TryParse(coordinates[0], out double lat)后,坐标的度数部分丢失了小数点,求技术同行帮忙排查解决。
解决方案
使用CultureInfo.InvariantCulture作为解析时的文化信息,即可解决该问题。
修正后的代码示例
string dataInput = "44.807222 14.000000, 44.759167 14.035556, 44.755000 14.011944, 44.794167 13.983333;44.800000 13.685278, 44.707222 13.733333, 44.685278 13.605833, 44.793889 13.496111;"; // Split on semicolon to get individual polygons string[] polygonStrings = dataInput.Split(';'); // Create a list to store GMapPolygons List<GMapPolygon> polygons = new List<GMapPolygon>(); foreach (var polygonString in polygonStrings) { // Split each polygon string on comma to get individual coordinates string[] coordStrings = polygonString.Trim().Split(','); // Create a list to store PointLatLng objects for each polygon List<PointLatLng> points = new List<PointLatLng>(); foreach (var coordString in coordStrings) { // Split each coordinate string on space to get latitude and longitude string[] coordinates = coordString.Trim().Split(' '); // Ensure there are two coordinates if (coordinates.Length == 2 && double.TryParse(coordinates[0], NumberStyles.Float, CultureInfo.InvariantCulture, out double lat) && double.TryParse(coordinates[1], NumberStyles.Float, CultureInfo.InvariantCulture, out double lon)) { // Create a PointLatLng object and add it to the list of points points.Add(new PointLatLng(lat, lon)); } else { Console.WriteLine($"Error parsing coordinates: {coordString}"); } } // Create Polygon GMapPolygon polygon = new GMapPolygon(points, "ime"); polygon.Fill = new SolidBrush(Color.FromArgb(0, Color.Blue)); polygon.Stroke = new Pen(Color.Red, 1); // Add the polygon to the list polygons.Add(polygon); }
内容的提问来源于stack exchange,提问作者nway
相关产品推荐
相关产品推荐

