如何:将字符串转换为数字(C# 编程指南)
你可通过使用 Convert 类中的方法将 string 转换为数字。 例如,当从命令行参数获取数值输入时,此类转换会很有用。 下表列出了可使用的一些方法。
数值类型 |
方法 |
---|---|
decimal |
|
float |
|
double |
|
short |
|
int |
|
long |
|
ushort |
|
uint |
|
ulong |
示例
此示例调用 ToInt32(String) 方法将输入的 string 转换为 int。 程序将捕获此方法可能引发的最常见的两个异常:FormatException 和 OverflowException。 如果该数字可以递增而不溢出整数存储位置,则程序使结果加上 1 并打印输出。
static void Main(string[] args)
{
int numVal = -1;
bool repeat = true;
while (repeat == true)
{
Console.WriteLine("Enter a number between −2,147,483,648 and +2,147,483,647 (inclusive).");
string input = Console.ReadLine();
// ToInt32 can throw FormatException or OverflowException.
try
{
numVal = Convert.ToInt32(input);
}
catch (FormatException e)
{
Console.WriteLine("Input string is not a sequence of digits.");
}
catch (OverflowException e)
{
Console.WriteLine("The number cannot fit in an Int32.");
}
finally
{
if (numVal < Int32.MaxValue)
{
Console.WriteLine("The new value is {0}", numVal + 1);
}
else
{
Console.WriteLine("numVal cannot be incremented beyond its current value");
}
}
Console.WriteLine("Go again? Y/N");
string go = Console.ReadLine();
if (go == "Y" || go == "y")
{
repeat = true;
}
else
{
repeat = false;
}
}
// Keep the console open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
// Sample Output:
// Enter a number between -2,147,483,648 and +2,147,483,647 (inclusive).
// 473
// The new value is 474
// Go again? Y/N
// y
// Enter a number between -2,147,483,648 and +2,147,483,647 (inclusive).
// 2147483647
// numVal cannot be incremented beyond its current value
// Go again? Y/N
// Y
// Enter a number between -2,147,483,648 and +2,147,483,647 (inclusive).
// -1000
// The new value is -999
// Go again? Y/N
// n
// Press any key to exit.
将 string 转换为 int 的另一种方法是使用 Int32 结构的 Parse 或 TryParse 方法。 ToUInt32 方法在内部使用 Parse。 如果字符串的格式无效,则 Parse 会引发一个异常;TryParse 不会引发异常,但会返回 false。 下面的示例演示了对 Parse 和 TryParse 的成功调用和不成功的调用。
int numVal = Int32.Parse("-105");
Console.WriteLine(numVal);
// Output: -105
// TryParse returns true if the conversion succeeded
// and stores the result in the specified variable.
int j;
bool result = Int32.TryParse("-105", out j);
if (true == result)
Console.WriteLine(j);
else
Console.WriteLine("String could not be parsed.");
// Output: -105
try
{
int m = Int32.Parse("abc");
}
catch (FormatException e)
{
Console.WriteLine(e.Message);
}
// Output: Input string was not in a correct format.
string inputString = "abc";
int numValue;
bool parsed = Int32.TryParse(inputString, out numValue);
if (!parsed)
Console.WriteLine("Int32.TryParse could not parse '{0}' to an int.\n", inputString);
// Output: Int32.TryParse could not parse 'abc' to an int.