How do I convert string to numerical value types?

Category: System, viewed: 2K time(s).

This examples show you how to convert string to its equivalent numerical values. To convert string into number type we can use the Parse method of the desired type such as the Int32.Parse(), Double.Parse().

using System;
using System.Globalization;
using System.Text;

namespace Kodecsharp.Example.System
{
    public class StringToNumber
    {
        public static void Main(string[] args)
        {
            string a = "97531";
            string b = "-135.79";

            //
            // Converted string that contains a number value to its 
            // numeric type. The NumberStyles tell the Double Parse
            // to allow decimal point and leading sign.
            //
            // The Parse method can throws FormatException when the
            // string doesn't contains numeric value.
            //
            int i = Int32.Parse(a);

            long l = long.Parse(a);
            
            float f = float.Parse(b);
            
            double d = Double.Parse(b, NumberStyles.AllowDecimalPoint | 
                NumberStyles.AllowLeadingSign);
            

            Console.WriteLine("A = " + i);
            Console.WriteLine("B = " + l);
            Console.WriteLine("C = " + f);
            Console.WriteLine("D = " + d);

            Console.ReadLine();
        }
    }
}

The static method Parse() is derived from the ValueType data type allow easy conversion from a string value to the specific value type. Type that support the Parse() method including Boolean, Byte, Decimal, Double, Int16, Int32, Int64, SByte, Single, UInt16, UInt32, UInt64.

Beside passing the string value to the Parse() method we can also pass a NumberStyles flag. This allows the Parse() method to handle specific properties of a number such as decimal point, currency symbol and leading or trailing signs.

Powered by Disqus