Share via


Cómo: Convertir una cadena en un número (Guía de programación de C#)

Puede convertir una cadena en un número usando métodos en la clase Convert. Este tipo de conversión puede resultar útil, por ejemplo, al obtener la entrada numérica de un argumento de línea de comandos. En la tabla siguiente se muestran algunos de los métodos que pueden usarse.

Tipo numérico

Método

decimal

ToDecimal(String)

float

ToSingle(String)

double

ToDouble(String)

short

ToInt16(String)

int

ToInt32(String)

long

ToInt64(String)

ushort

ToUInt16(String)

uint

ToUInt32(String)

ulong

ToUInt64(String)

Ejemplo

En este ejemplo, se llama al método ToInt32(String) para convertir una cadena de entrada en un valor int. El programa detecta las dos excepciones más comunes que este método puede producir, FormatException y OverflowException. Si se puede incrementar el número sin que se produzca un desbordamiento de la ubicación de almacenamiento de los enteros, el programa agregará 1 al resultado e imprimirá el resultado.

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.

Otra forma de convertir string en int es mediante los métodos Parse o TryParse del struct Int32. El método ToUInt32 utiliza Parse internamente. Si el formato de la cadena no es válido, Parse produce una excepción, mientras que TryParse no produce ninguna excepción, pero devuelve false. En los siguientes ejemplos se muestran llamadas correctas e incorrectas a Parse y 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.

Vea también

Tareas

Cómo: Determinar si una cadena representa un valor numérico (Guía de programación de C#)

Referencia

Tipos (Guía de programación de C#)

Otros recursos

Utilidad de formato de .NET Framework 4