Come convertire una stringa in un numero (Guida per programmatori C#)

Si converte un oggetto string in un numero chiamando il Parse metodo o TryParse trovato nei tipi numerici (int, long, doublee così via) o usando i metodi nella System.Convert classe .

È leggermente più efficiente e semplice chiamare un TryParse metodo (ad esempio, int.TryParse("11", out number)) o Parse (ad esempio, var number = int.Parse("11")). L'uso di un metodo Convert è più utile per gli oggetti generali che implementano IConvertible.

Si usano Parse metodi o TryParse nel tipo numerico previsto che la stringa contiene, ad esempio il System.Int32 tipo . Il metodo Convert.ToInt32 utilizza il metodo Parse internamente. Il metodo restituisce il numero convertito. Il ParseTryParse metodo restituisce un valore booleano che indica se la conversione è riuscita e restituisce il numero convertito in un out parametro. Se la stringa non è in un formato valido, Parse genera un'eccezione, ma TryParse restituisce false. Quando si chiama un Parse metodo, è consigliabile usare sempre la gestione delle eccezioni per intercettare un FormatException oggetto quando l'operazione di analisi non riesce.

Chiamare i metodi Parse o TryParse

I Parse metodi e TryParse ignorano gli spazi vuoti all'inizio e alla fine della stringa, ma tutti gli altri caratteri devono essere caratteri che formano il tipo numerico appropriato (int, long, ulongfloat, decimal, e così via). Gli spazi vuoti all'interno della stringa che sostituisce il numero generano un errore. Ad esempio, è possibile usare decimal.TryParse per analizzare "10", "10.3" o " 10 ", ma non è possibile usare questo metodo per analizzare 10 da "10X", "1 0" (si noti lo spazio incorporato), "10 .3" (si noti lo spazio incorporato), "10e1" (float.TryParse funziona qui) e così via. Stringa il cui valore è null o String.Empty non riesce ad analizzare correttamente. È possibile cercare una stringa vuota o Null prima di tentare di analizzarla chiamando il metodo String.IsNullOrEmpty.

L'esempio seguente illustra le chiamate con esito positivo e negativo per Parse e TryParse.

using System;

public static class StringConversion
{
    public static void Main()
    {
        string input = String.Empty;
        try
        {
            int result = Int32.Parse(input);
            Console.WriteLine(result);
        }
        catch (FormatException)
        {
            Console.WriteLine($"Unable to parse '{input}'");
        }
        // Output: Unable to parse ''

        try
        {
            int numVal = Int32.Parse("-105");
            Console.WriteLine(numVal);
        }
        catch (FormatException e)
        {
            Console.WriteLine(e.Message);
        }
        // Output: -105

        if (Int32.TryParse("-105", out int j))
        {
            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.

        const string inputString = "abc";
        if (Int32.TryParse(inputString, out int numValue))
        {
            Console.WriteLine(numValue);
        }
        else
        {
            Console.WriteLine($"Int32.TryParse could not parse '{inputString}' to an int.");
        }
        // Output: Int32.TryParse could not parse 'abc' to an int.
    }
}

Nell'esempio seguente viene illustrato un approccio all'analisi di una stringa prevista per includere caratteri numerici iniziali (inclusi caratteri esadecimali) e caratteri non numerici finali. I caratteri validi dall'inizio di una stringa vengono assegnati a una nuova stringa prima di chiamare il metodo TryParse. Poiché le stringhe da analizzare contengono alcuni caratteri, nell'esempio viene chiamato il String.Concat metodo per assegnare caratteri validi a una nuova stringa. Per una stringa più grande, è invece possibile usare la classe StringBuilder.

using System;

public static class StringConversion
{
    public static void Main()
    {
        var str = "  10FFxxx";
        string numericString = string.Empty;
        foreach (var c in str)
        {
            // Check for numeric characters (hex in this case) or leading or trailing spaces.
            if ((c >= '0' && c <= '9') || (char.ToUpperInvariant(c) >= 'A' && char.ToUpperInvariant(c) <= 'F') || c == ' ')
            {
                numericString = string.Concat(numericString, c.ToString());
            }
            else
            {
                break;
            }
        }

        if (int.TryParse(numericString, System.Globalization.NumberStyles.HexNumber, null, out int i))
        {
            Console.WriteLine($"'{str}' --> '{numericString}' --> {i}");
        }
        // Output: '  10FFxxx' --> '  10FF' --> 4351

        str = "   -10FFXXX";
        numericString = "";
        foreach (char c in str)
        {
            // Check for numeric characters (0-9), a negative sign, or leading or trailing spaces.
            if ((c >= '0' && c <= '9') || c == ' ' || c == '-')
            {
                numericString = string.Concat(numericString, c);
            }
            else
            {
                break;
            }
        }

        if (int.TryParse(numericString, out int j))
        {
            Console.WriteLine($"'{str}' --> '{numericString}' --> {j}");
        }
        // Output: '   -10FFXXX' --> '   -10' --> -10
    }
}

Chiamare i metodi Convert

Nella tabella seguente sono elencati alcuni dei metodi della classe Convert che è possibile usare per convertire una stringa in numero.

Tipo numerico metodo
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)

Nell'esempio seguente viene chiamato il Convert.ToInt32(String) metodo per convertire una stringa di input in un valore int. Nell'esempio vengono rilevate le due eccezioni più comuni generate da questo metodo: FormatException e OverflowException. Se il numero risultante può essere incrementato senza superare Int32.MaxValue, l'esempio aggiunge 1 al risultato e visualizza l'output.

using System;

public class ConvertStringExample1
{
    static void Main(string[] args)
    {
        int numVal = -1;
        bool repeat = true;

        while (repeat)
        {
            Console.Write("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);
                if (numVal < Int32.MaxValue)
                {
                    Console.WriteLine("The new value is {0}", ++numVal);
                }
                else
                {
                    Console.WriteLine("numVal cannot be incremented beyond its current value");
                }
           }
            catch (FormatException)
            {
                Console.WriteLine("Input string is not a sequence of digits.");
            }
            catch (OverflowException)
            {
                Console.WriteLine("The number cannot fit in an Int32.");
            }

            Console.Write("Go again? Y/N: ");
            string? go = Console.ReadLine();
            if (go?.ToUpper() != "Y")
            {
                repeat = false;
            }
        }
    }
}
// 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