C#字符串转换为float

 

1、解决不同计算机上,区域和时间不同而引起的转换问题(如:“123.456”报“字符串格式不正确”问题

//解决区域、语言变更引起的“识别不出小数点问题”如:转换时“123.456”转换时不认识"."

    /// <summary>
    /// 数学转换类
    /// </summary>
    public class MathConverter
    {

        /// <summary>
        /// object 转换 float(转换失败,则尝试将前部分数字转换为float)
        /// </summary>
        /// <param name="obj2Float"></param>
        /// <returns>默认:0.00</returns>
        public static float ObjectToFloat(object obj2Float)
        {
            float result = 0.00f;   //默认值
            if (obj2Float != null)
            {
                string str2Float = obj2Float.ToString();        //object to string
                if (!float.TryParse(str2Float, out result))     //string直接转换为float,若失败,则获取字符串前部分数字转换为float
                {
                    string strNumber = string.Empty;
                    foreach(char iChr in str2Float)             
                    {
                        if(Char.IsNumber(iChr))
                        {
                            strNumber += iChr;
                        }
                        else
                        {
                            break;
                        }
                    }
                    if(!string.IsNullOrEmpty(strNumber))
                    {
                        float.TryParse(strNumber, out result);
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// object 转换 float(转换失败,则尝试将前部分数字转换为float)
        /// </summary>
        /// <param name="obj2Float"></param>
        /// <param name="result">默认:0.00f</param>
        /// <returns>false : 转换失败</returns>
        public static bool TryObjectToFloat(object obj2Float, out float result)
        {
            bool isSuccess = false;
            result = 0.00f;   //默认值
            if (obj2Float != null)
            {
                string str2Float = obj2Float.ToString();        //object to string
                if (!float.TryParse(str2Float, out result))     //string直接转换为float,若失败,则获取字符串前部分数字转换为float
                {
                    string strNumber = string.Empty;
                    foreach (char iChr in str2Float)
                    {
                        if (Char.IsNumber(iChr))
                        {
                            strNumber += iChr;
                        }
                        else
                        {
                            break;
                        }
                    }
                    if (!string.IsNullOrEmpty(strNumber))
                    {
                        if(float.TryParse(strNumber, out result))
                        {
                            isSuccess = true;
                        }
                    }
                }
                else
                {
                    isSuccess = true;
                }
            }
            return isSuccess;
        }
    }
View Code

 

posted @ 2017-12-15 14:10  慧由心生  阅读(9364)  评论(0编辑  收藏  举报