Parse a string with leading and trailing white space, and currency symbol to float in CSharp

Description

The following code shows how to parse a string with leading and trailing white space, and currency symbol to float.

Example


  // www  .j a  v a 2 s .  c  om
  
  
  

using System;
using System.Globalization;
using System.Threading;

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

      string value;
      NumberStyles styles;


      value = " $ 6,1.3299  ";
      styles = NumberStyles.Number | NumberStyles.AllowCurrencySymbol;
      ShowNumericValue(value, styles);
   }

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

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