using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyClassLibrary.MyCalculate
{
///
/// 进行字符形式数字转换的类
///
public static class MyTryParseClass
{
///
/// 将所给出的整数数字字符串表现形式转换为等效32位无符整数,一个指示转换是否成功的bool值
///
/// 传入的字符数字
/// 得到的结果32位无符号×××数字
/// 返回是否成功
public static bool MyTryParse(string strNumber, out int resNumber)
{
resNumber = 0;
char[] chs = strNumber.ToArray();
if (chs[0] == '-')
{
char[] chss = (strNumber.Substring(1)).ToCharArray();
for (int i = 0; i < chss.Length; i++)
{
if ((int)chss[i] >= 48 && (int)chss[i] <= 57)
{
resNumber += (int)(((int)chss[i] - 48) * (Math.Pow(10, (chss.Length - i - 1))));
if (resNumber == int.MinValue && i == 0)
{
return false;
}
}
else
{
return false;
}
}
resNumber = -resNumber;
}
else
{
for (int i = 0; i < chs.Length; i++)
{
if ((int)chs[i] >= 48 && (int)chs[i] <= 57)
{
resNumber += (int)(((int)chs[i] - 48) * (Math.Pow(10, (chs.Length - i - 1))));
}
else
{
return false;
}
}
}
if (resNumberint.MinValue)
{
return true;
}
else
{
return false;
}
}
///
///将所给出的浮点型数字字符串表现形式转换为等效双精度浮点数,一个指示转换是否成功的bool值
///
/// 传入的字符数字
/// 得到的结果浮点型数字
/// 返回是否成功
public static bool MyTryParse(string strNumber, out double resNumber)
{
resNumber = 0.0;
int num1 = 0;//小数点前的数字
int num2 = 0;//小数点后的数字
#region 负数情况
if (strNumber[0] == '-')
{
string[] strNum = strNumber.Split(new char[] {'.','-'});
//整数部分
char[] chss = strNum[1].ToCharArray();
for (int i = 0; i < chss.Length; i++)
{
if ((int)chss[i] >= 48 && (int)chss[i] <= 57)
{
num1 += (int)(((int)chss[i] - 48) * (Math.Pow(10, chss.Length-i-1)));
if (num1 == int.MinValue && i == 0)
{
return false;
}
}
else
{
return false;
}
}
//小数部分
char[] chs = strNum[2].ToCharArray();
for (int i = 0; i < chs.Length; i++)
{
if ((int)chs[i] >= 48 && (int)chs[i] <= 57)
{
num2 += (int)(((int)chs[i] - 48) * (Math.Pow(10, (chs.Length-i-1))));
if (num2 == int.MinValue && i == 0)
{
return false;
}
}
else
{
return false;
}
}
resNumber = -(num1 + num2 * (Math.Pow(10, (-1) * strNum[2].Length)));
}
#endregion
#region 正数情况
else
{
string[] strNum = strNumber.Split('.');
//整数部分
char[] chs = strNum[0].ToCharArray();
for (int i = 0; i < chs.Length; i++)
{
if ((int)chs[i] >= 48 && (int)chs[i] <= 57)
{
num1 += (int)(((int)chs[i] - 48) * (Math.Pow(10, (chs.Length - i - 1))));
}
else
{
return false;
}
}
//小数部分
char[] chss = strNum[1].ToCharArray();
for (int i = 0; i < chss.Length; i++)
{
if ((int)chss[i] >= 48 && (int)chss[i] <= 57)
{
num2 += (int)(((int)chss[i] - 48) * (Math.Pow(10, (chss.Length - i - 1))));
}
else
{
return false;
}
}
resNumber = num1 + num2 * (Math.Pow(10, (-1) * strNum[1].Length));
}
#endregion
if (resNumber > double.MinValue && resNumber <= double.MaxValue)
{
return true;
}
else
{
return false;
}
}
}
}