Convert string in a specified style and culture-specific format to float in CSharp

Description

The following code shows how to convert string in a specified style and culture-specific format to float.

Example


using System;/* w w  w. java 2s  .  c  o  m*/
using System.Globalization;

public class Example
{
    public static void Main()
    {
      string[] values = { " 987.654E-21", " 987,654E-21",  "(98765,43210.12345)", 
                          "9,876,543.210", "9.876.543,210",  "98_76_54_32,19" };


      CultureInfo ci = new CultureInfo("");
      ci.NumberFormat.NumberGroupSizes = new int[] { 2 };
      ci.NumberFormat.NumberGroupSeparator = "_";

      CultureInfo[] providers = { new CultureInfo("en-US"),new CultureInfo("nl-NL"), ci };       

      NumberStyles[] styles = { NumberStyles.Currency, NumberStyles.Float };

      foreach (CultureInfo provider in providers)
      {
         foreach (string value in values)
         {
            foreach (NumberStyles style in styles)
            {
               try {
                  float number = Single.Parse(value, style, provider);            
                  Console.WriteLine("{0} ({1}) -> {2}", value, style, number);
               }
               catch (FormatException) {
                  Console.WriteLine("'{0}' is invalid using {1}.", value, style);
               }
               catch (OverflowException) {
                  Console.WriteLine("'{0}' is out of the range of a Single.", value);
               } 
            }            
         }         
      }
   }   
}

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