C#字符串转换为float
标签:for else pre style turn closed return 字符 bre
1、解决不同计算机上,区域和时间不同而引起的转换问题(如:“123.456”报“字符串格式不正确”问题)
///
/// 数学转换类
///
public class MathConverter
{
///
/// object 转换 float(转换失败,则尝试将前部分数字转换为float)
///
///
/// 默认:0.00
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;
}
///
/// object 转换 float(转换失败,则尝试将前部分数字转换为float)
///
///
/// 默认:0.00f
/// false : 转换失败
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;
}
}
View Code
C#字符串转换为float
标签:for else pre style turn closed return 字符 bre
原文地址:http://www.cnblogs.com/shenchao/p/8042785.html
评论