C# Single Parse(String, NumberStyles)

Description

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

Syntax

Single.Parse(String, NumberStyles) has the following syntax.


public static float Parse(
  string s,
  NumberStyles style
)

Parameters

Single.Parse(String, NumberStyles) has the following parameters.

Returns

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

Example

The following example uses the Parse(String, NumberStyles) method to parse the string representations of Single values.


using System;//from   w  w  w  .  j  a  v  a2s .  c  om
using System.Globalization;
using System.Threading;

public class ParseString
{
   public static void Main()
   {
      Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");

      string value;
      NumberStyles styles;

      // Parse a string in exponential notation with only the AllowExponent flag.  
      value = "-1.234E-02";
      styles = NumberStyles.AllowExponent;
      ShowNumericValue(value, styles);

      // Parse a string in exponential notation 
      // with the AllowExponent and Number flags.
      styles = NumberStyles.AllowExponent | NumberStyles.Number;
      ShowNumericValue(value, styles);

      // Parse a currency value with leading and trailing white space, and 
      // white space after the U.S. currency symbol. 
      value = " $ 1,234.5678  ";
      styles = NumberStyles.Number | NumberStyles.AllowCurrencySymbol;
      ShowNumericValue(value, styles);

      // Parse negative value with thousands separator and decimal. 
      value = "(4,321.98)";
      styles = NumberStyles.AllowParentheses | NumberStyles.AllowTrailingSign |
               NumberStyles.Float; 
      ShowNumericValue(value, styles);

      styles = NumberStyles.AllowParentheses | NumberStyles.AllowTrailingSign |
               NumberStyles.Float | NumberStyles.AllowThousands;
      ShowNumericValue(value, styles);
   }

   private static void ShowNumericValue(string value, NumberStyles styles)
   {
      Single number = Single.Parse(value, styles);
      Console.WriteLine("Converted '{0}' using {1} to {2}.", 
                           value, styles.ToString(), number);
   }   
}

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