CSharp - Format NumberStyles Type

Introduction

Each numeric type defines a static Parse method that accepts a NumberStyles argument.

NumberStyles is a flags enum to control how to convert string to a numeric type.

It has the following combinable members:

  • AllowCurrencySymbol
  • AllowDecimalPoint
  • AllowExponent
  • AllowHexSpecifier
  • AllowLeadingSign
  • AllowLeadingWhite
  • AllowParentheses
  • AllowThousands
  • AllowTrailingSign
  • AllowTrailingWhite

NumberStyles defines these composite members:

  • None
  • Integer
  • Float
  • Number
  • HexNumber
  • Currency
  • Any

Except for None, all composite values include AllowLeadingWhite and AllowTrailingWhite.

Demo

using System;
using System.Globalization;

class MainClass//from  w w w .j  a v  a2  s.co  m
{
    public static void Main(string[] args)
    {

        int thousand = int.Parse("3E8", NumberStyles.HexNumber);
        int minusTwo = int.Parse("(2)", NumberStyles.Integer |
                                         NumberStyles.AllowParentheses);
        double aMillion = double.Parse("1,000,000", NumberStyles.Any);
        Console.WriteLine(aMillion);

        decimal threeMillion = decimal.Parse("3e6", NumberStyles.Any);
        Console.WriteLine(threeMillion);

        decimal fivePointTwo = decimal.Parse("$5.20", NumberStyles.Currency);
        Console.WriteLine(fivePointTwo);

    }
}

Result

The following code hardcoded to work with the euro sign and a blank group separator for currencies:

NumberFormatInfo ni = new NumberFormatInfo();
ni.CurrencySymbol = "C";
ni.CurrencyGroupSeparator = " ";
double million = double.Parse ("C1 000 000", NumberStyles.Currency, ni);