C# Single Parse(String)

Description

Single Parse(String) converts the string representation of a number to its single-precision floating-point number equivalent.

Syntax

Single.Parse(String) has the following syntax.


public static float Parse(
  string s
)

Parameters

Single.Parse(String) has the following parameters.

  • s - A string that contains a number to convert.

Returns

Single.Parse(String) method returns A single-precision floating-point number equivalent to the numeric value or symbol specified in s.

Example

The following example uses the Parse(String) method to convert an array of strings to equivalent Single values.


//ww  w . j ava  2s  .com
using System;

public class Example
{
   public static void Main()
   {
      string[] values = { "123", "(123)", "-123,456,789", "123.45e+6", 
                          "+543", "5e2", "3.1416", "600.", "-.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 »
    System »




Array
BitConverter
Boolean
Byte
Char
Console
ConsoleKeyInfo
Convert
DateTime
DateTimeOffset
Decimal
Double
Enum
Environment
Exception
Guid
Int16
Int32
Int64
Math
OperatingSystem
Random
SByte
Single
String
StringComparer
TimeSpan
TimeZone
TimeZoneInfo
Tuple
Tuple
Tuple
Type
UInt16
UInt32
UInt64
Uri
Version