String Number Parsing in C#
At some point of time, we need to parse a number which is represented in string format. C# has NumberStyles Enum which helps enormously for parsing.
To proceed with the examples, you need to refer to System.Globalization namespace.
The following examples would show you the actual parsed values against the formatted string representation.
Using the NumberStyles.AllowCurrencySymbol enum the currency symbol is accepted by the Parse method.
A set of parentheses are allowed using the NumberStyles.AllowParenthese enum. The set of parentheses represented is actually referred to a negative value. So the output of the parsed value will always be in negative.
A comma (,) is used to separate thousands in number format. The NumberStyle.AllowThousands enum, allows the comma to be parsed.
A trailing sign is provide, usually – (negative) or + (positive) for formatting reasons. The Numberstyles.AllowTrailingSign parses the positive or negative number with the respective trailing sign.
Often this enum is used for omitting trailing spaces from the original value. The NumberStyles.AllowTrailingWhite is used.
Combining Number Styles
NumberStyles enum is Flags enabled, so we can combine the values. The following examples show that combinations are helpful in parsing number formatted strings.
It is safe to handle the error while parsing the string formatted data. The NumberStyles could be used with the TryParse static method. As you see in the following example, the result is set to the parsed value if there is no error parsing. And the return value of the TryParse method is a bool, which could be checked for Parse success or failure.
A custom number format also could be parsed. As you see in the following code, the parse throws an error saying “Input string was not in a correct format”. However the NumberStyles are used properly.
To fix this, you need to provide a NumberFormatInfo object to the method as parameter. As you see in the following code, the CurrencySymbol property has the allowable format. And the output of the parse is a success with the NumberFormatInfo object.
Hope this post is useful.
Thanks for reading. Like Method Of Tried in Facebook.