Export (0) Print
Expand All

Convert.ToSingle Method (String)

Converts the specified String representation of a number to an equivalent single-precision floating point number.

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)

public static float ToSingle(
	string value
)

Parameters

value
Type: System.String
A String containing a number to convert.

Return Value

Type: System.Single
A single-precision floating point number equivalent to the value of value.
-or-
Zero if value is null.

ExceptionCondition
FormatException

value is not a number in a valid format.

OverflowException

value represents a number less than MinValue or greater than MaxValue.

The return value is the result of invoking the Single.Parse method on value.

If you prefer not to handle an exception if the conversion fails, you can call the Single.TryParse method instead. It returns a Boolean value that indicates whether the conversion succeeded or failed.

The following code sample illustrates the conversion of a String to Single, using ToSingle:


public void ConvertStringFloat(string stringVal)
{
   float floatVal = 0;

   try
   {
      floatVal = System.Convert.ToSingle(stringVal);
      outputBlock.Text += String.Format(
         "The string as a float is {0}.", floatVal) + "\n";
   }
   catch (System.OverflowException)
   {
      outputBlock.Text += String.Format(
         "The conversion from string-to-float overflowed.") + "\n";
   }
   catch (System.FormatException)
   {
      outputBlock.Text += String.Format(
         "The string is not formatted as a float.") + "\n";
   }
   catch (System.ArgumentNullException)
   {
      outputBlock.Text += String.Format(
         "The string is null.") + "\n";
   }

   // Float to string conversion will not overflow.
   stringVal = System.Convert.ToString(floatVal);
   outputBlock.Text += String.Format(
      "The float as a string is {0}.", stringVal) + "\n";
}


Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

XNA Framework

Supported in: Xbox 360, Windows Phone OS 7.0

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.

Community Additions

ADD
Show:
© 2014 Microsoft