Convert string to float with default settings in CSharp

Description

The following code shows how to convert string to float with default settings.

Example


using System;/*from w w  w.j  a  va  2s.c  om*/

public class Example
{
   public static void Main()
   {
      string[] values = { "(100)", "-123,456,789", "123.45e+6", 
                          "+500", "5e2", "3.1", "6.", "-.123", 
                          "-Infinity", "-1E-16", Double.MaxValue.ToString(), 
                          Single.MinValue.ToString(), String.Empty };
      foreach (string value in values)
      {
         try {   
            float number = Single.Parse(value);
            Console.WriteLine("{0} -> {1}", value, number);
         }
         catch (FormatException) {
            Console.WriteLine("'{0}' is not in a valid format.", value);
         }
         catch (OverflowException) {
            Console.WriteLine("{0} is outside the range of a Single.", value);
         }
      }                                  
   }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Data Types »




C# Data Types
Bool
Byte
Char
Decimal
Double
Float
Integer
Long
Short
String
C# Array
Array Example
Byte Array
C# Standard Data Type Format
BigInteger
Complex
Currency
DateTime
DateTimeOffset
DateTime Format Parse Convert
TimeSpan
TimeZone
Enum
Null
tuple
var