1、解决不同计算机上,区域和时间不同而引起的转换问题(如:“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(str2Float, 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(str2Float, out result)) { isSuccess = true; } } } else { isSuccess = true; } } return isSuccess; } }