C# Single TryParse(String, Single)

Description

Single TryParse(String, Single) converts the string representation of a number to its single-precision floating-point number equivalent. A return value indicates whether the conversion succeeded or failed.

Syntax

Single.TryParse(String, Single) has the following syntax.


public static bool TryParse(
  string s,
  out float result
)

Parameters

Single.TryParse(String, Single) has the following parameters.

  • s - A string representing a number to convert.
  • result - When this method returns, contains single-precision floating-point number equivalent to the numeric value or symbol contained in s, if the conversion succeeded, or zero if the conversion failed. The conversion fails if the s parameter is null or String.Empty, is not a number in a valid format, or represents a number less than MinValue or greater than MaxValue. This parameter is passed uninitialized.

Returns

Single.TryParse(String, Single) method returns true if s was converted successfully; otherwise, false.

Example

The following example uses the TryParse(String, Single) method to convert the string representations of numeric values to Single values.


/*from www .  j  a v  a 2  s .  c  om*/
using System;
public class MainClass{
  public static void Main(String[] argv){  
    string value;
    float number;
    
    // Parse a floating-point value with a thousands separator. 
    value = "1,234.56";
    if (Single.TryParse(value, out number))
       Console.WriteLine(number);
    else
       Console.WriteLine("Unable to parse '{0}'.", value);      
    
    // Parse a floating-point value with a currency symbol and a  
    // thousands separator. 
    value = "$1,234.56";
    if (Single.TryParse(value, out number))
       Console.WriteLine(number);
    else
       Console.WriteLine("Unable to parse '{0}'.", value);   
    
    // Parse value in exponential notation. 
    value = "-1.234e6";
    if (Single.TryParse(value, out number))
       Console.WriteLine(number);
    else
       Console.WriteLine("Unable to parse '{0}'.", value);   
    
    // Parse a negative integer value. 
    value = "-123456787123456781";
    if (Single.TryParse(value, out number))
       Console.WriteLine(number);
    else
       Console.WriteLine("Unable to parse '{0}'.", 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