Unity之修复个别手机小数精度问题

部分手机字符串转小数时,可能会出现精度问题,用如下接口代替 float.Parse()和float.TryParse()可解决问题,代码如下:

 1     static StringBuilder s_sb = new StringBuilder();
 2     
 3     
 4     public static bool TryParseFloat(this string strFloat, out float result)
 5     {
 6         result = 0;
 7         if (string.IsNullOrEmpty(strFloat))
 8             return false;
 9 
10         int indexOfDot = strFloat.IndexOf('.');
11         if (indexOfDot < 0)
12             return float.TryParse(strFloat, out result);
13 
14         int curDecimalCount = strFloat.Length - indexOfDot - 1;
15         int clipCount = curDecimalCount - 4;
16         string str;
17         if (clipCount > 0)
18         {
19             int newLen = strFloat.Length - clipCount;
20             str = strFloat.Substring(0, newLen);
21         }
22         else if (clipCount == 0)
23         {
24             str = strFloat;
25         }
26         else
27         {
28             s_sb.Length = 0;
29             s_sb.Append(strFloat);
30             clipCount = -clipCount;
31             for (int i = 0; i < clipCount; i++)
32                 s_sb.Append("0");
33             str = s_sb.ToString();
34         }
35         str = str.Replace(".", "");
36 
37         if (int.TryParse(str, out int result2))
38         {
39             result = result2 / 10000f;
40             return true;
41         }
42 
43         return false;
44     }
45 
46     public static float ParseFloat(this string strFloat)
47     {
48         if (string.IsNullOrEmpty(strFloat))
49             return 0;
50 
51         strFloat.TryParseFloat(out float result);
52         return result;
53     }

 

转载请注明出处:https://www.cnblogs.com/jietian331/p/15469774.html

posted @ 2021-10-27 11:27  孤独の巡礼  阅读(186)  评论(0编辑  收藏  举报