Using NumberStyles to parse numbers in C# .NET Part 1
March 11, 2015 1 Comment
There are a lot of number formats out there depending on the industry we’re looking at. E.g. negative numbers can be represented in several different ways:
- -14
- (14)
- 14-
- 14.00-
- (14,00)
…and so on. Accounting, finance and other, highly “numeric” fields will have their own standards to represent numbers. Your application may need to parse all these strings and convert them into proper numeric values. The static Parse method of the numeric classes, like int, double, decimal all accept a NumberStyles enumeration. This enumeration is located in the System.Globalization namespace.
The following bit of code will throw a FormatException:
string rawNumber = "(14)"; int parsed = int.Parse(rawNumber);
However, as soon as you add a special NumberStyles enumeration value the code will pass:
string rawNumber = "(14)"; int parsed = int.Parse(rawNumber, NumberStyles.AllowParentheses);
“parsed” will be correctly set to -14.
You can combine the enumeration flags. Say that you need to convert “$(14)”, i.e. -14 dollars. Here’s a possible solution:
int parsed = int.Parse(rawNumber, NumberStyles.AllowParentheses | NumberStyles.AllowCurrencySymbol);
Note that the above method may fail depending on the current culture settings of the thread our program is running in. If you’re running with the US culture then the $ sign will be accepted otherwise the above method will fail. My PC is set to the Swedish culture se-SV. The Swedish currency is abbreviated by “kr” so I actually got an exception when I ran the above method. In my case I had to modify the currency symbol to “kr” as follows:
string rawNumber = "kr(14)"; int parsed = int.Parse(rawNumber, NumberStyles.AllowParentheses | NumberStyles.AllowCurrencySymbol);
“parsed” was set to -14 as expected. This is not the only solution though. We’ll look at the NumberStyles enumeration more in the next part.
View all posts related to Globalization here.
Reblogged this on Brian By Experience.