.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就解決了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM