.net double类型转string类型的坑

之前项目当中的接入的高德逆地理编码功能偶尔会出现参数错误的bug,经过排查服务端异常log,发现请求的url中的location参数中的小数点变成了逗号。

代码如下

        public async Task<MapResult> GetMapResultAsync(double lat, double lng)
        {
            string url = string.Format("http://restapi.amap.com/v3/geocode/regeo?output=json&location={0},{1}&key={2}", 
                lng.ToString(), lat.ToString(), GouldAk);
            GolderMapResult res;
            try
            {

                string json = await HttpHelper.GetAsync(url);
                json = json.Replace("[]", "\"\"");
                res = JsonConvert.DeserializeObject<GolderMapResult>(json);
                if (res.resultBase.addressComponentBase.city.IsNullOrWhiteSpace())
                    res.resultBase.addressComponentBase.city = res.resultBase.addressComponentBase.province;
            }
            catch (Exception ex)
            {
                Logger.Error("请求高德地图失败:" + url);
                throw ex;
            }
            if (res.status != 1)
            {
                Logger.Error("请求高德地图失败");
                throw new UserFriendlyException("请求高德地图失败,状态码:" + res.status + " 说明:" + res.info + " url:" + url);
            }
                
            return res;
        }

其中 lng.ToString(), lat.ToString() 转换string的时候,偶尔会把中间的点号转成逗号,于是造成高德api返回参数错误。

后来在网上查找原因,参考这篇博客http://blog.chinaunix.net/uid-9255716-id-107923.html

对于用“.”分隔千位,用“,”分隔小数的国家,1,234.56 将会格式化成 1.234,56。如果您需要结果无论在什么语言下都是一样的,就请使用 CultureInfo.InvariantCulture 作为语言。

接下来就简单了,贴修改后的代码

        public async Task<MapResult> GetMapResultAsync(double lat, double lng)
        {
            string url = string.Format("http://restapi.amap.com/v3/geocode/regeo?output=json&location={0},{1}&key={2}", 
                lng.ToString(CultureInfo.InvariantCulture), lat.ToString(CultureInfo.InvariantCulture), GouldAk);
            GolderMapResult res;
            try
            {

                string json = await HttpHelper.GetAsync(url);
                json = json.Replace("[]", "\"\"");
                res = JsonConvert.DeserializeObject<GolderMapResult>(json);
                if (res.resultBase.addressComponentBase.city.IsNullOrWhiteSpace())
                    res.resultBase.addressComponentBase.city = res.resultBase.addressComponentBase.province;
            }
            catch (Exception ex)
            {
                Logger.Error("请求高德地图失败:" + url);
                throw ex;
            }
            if (res.status != 1)
            {
                Logger.Error("请求高德地图失败");
                throw new UserFriendlyException("请求高德地图失败,状态码:" + res.status + " 说明:" + res.info + " url:" + url);
            }
                
            return res;
        }

只是把 lng.ToString(), lat.ToString() 替换成了 lng.ToString(CultureInfo.InvariantCulture), lat.ToString(CultureInfo.InvariantCulture) ,这样这个bug就解决了。

posted @ 2019-01-15 11:22  Woody~~~  阅读(1186)  评论(5编辑  收藏  举报