CSharp - Parsing with format providers

Introduction

C# data type overloads static Parse and TryParse method to accept a format provider, and optionally, a NumberStyles or DateTimeStyles enum.

NumberStyles and DateTimeStyles control how parsing work.

They specify controls whether parentheses or a currency symbol can appear in the input string.

For example:

Demo

using System;
using System.Globalization;

class MainClass//from  w ww  .  j av  a  2s  .  co m
{
    public static void Main(string[] args)
    {
        int error = int.Parse("(2)");   // Exception thrown

        int minusTwo = int.Parse("(2)", NumberStyles.Integer |
                                         NumberStyles.AllowParentheses);   // OK

        Console.WriteLine(minusTwo);
        decimal fivePointTwo = decimal.Parse("$5.20", NumberStyles.Currency,
                               CultureInfo.GetCultureInfo("en-US"));
        Console.WriteLine(fivePointTwo);

    }
}

Result