Pranay Rana: Parsing Number with NumberStyles

Sunday, July 15, 2018

Parsing Number with NumberStyles

Parsing string value to number i.e. converting string representation of number into number type is one of the basic task and most of programming language provides support to perform it easily. But sometimes developer writes too much complex code to perform this (string to number parsing) task as not aware about the easy way provided by programming language.

Below is small tip about parsing string representation of number to number type with respect to C# language. C# language has below numeric types 
  • integer types (sbyte, short, int, long, byte, ushort, uint, ulong),  
  • non-integer (number with precision or floating) types (float, decimal) 
and to convert string value in one of the above listed numeric type, C# language provide two methods


Above two method allows to convert string representation of number to string. For Example

int number = int.Parse("1234");
//or
//int number = -1;
//bool isPased = int.TryParse("1234", out number);
Console.WriteLine(number);

But it fails (i.e. throws run-time exception) when you try input as below

int parsedNumber = int.Parse(" -1234 ");
int parsedNumber = int.Parse("(1234)");
int parsedNumber = int.Parse("$1234");
int parsedNumber = int.Parse("1,234");
int parsedNumber = int.Parse(" (1,234) ")

So above all tried input throws run-time exception , but solution to is make use of overload of Parse and TryParse which comes with NumberStyles as input. Below is screen shot of overload of Parse method

below is code make use of overload and avoid run-time exception.

//output: -1234
int parsedNumber = int.Parse("(1234)", NumberStyles.AllowParentheses);

// output: 1234
int parsedNumber = int.Parse("1,234", NumberStyles.AllowThousands);

// output: -1234
int parsedNumber = int.Parse(" -1234  ", NumberStyles.AllowTrailingWhite |
                                              NumberStyles.AllowLeadingWhite |
                                              NumberStyles.AllowLeadingSign);

// output: -1234
int parsedNumber = int.Parse(" (1,234) ", NumberStyles.AllowTrailingWhite |
                                          NumberStyles.AllowLeadingWhite |
                                     NumberStyles.AllowParentheses |
                                          NumberStyles.AllowThousands);

// allows currency symbol
// output: 1234
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
int parsedNumber4 = int.Parse("$1234", NumberStyles.Currency);

Different number allows different input values. As given in above code one can put logic OR between  different value of NumberStyles and allows combination to permit various input format.

Try out other values of NumberStyles listed at MSDN: https://msdn.microsoft.com/en-us/library/system.globalization.numberstyles(v=vs.110).aspx  

No comments:

Post a Comment