Using NumberStyles to parse numbers in C# .NET Part 1

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.

Advertisement

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

One Response to Using NumberStyles to parse numbers in C# .NET Part 1

  1. Brian Dead Rift Webb says:

    Reblogged this on Brian By Experience.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: