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

In the previous post we looked at some basic usage of the NumberStyles enumeration. The enumeration allows to parse other representations of numeric values.

Occasionally negative numbers are shown with a trailing negative sign like this: “13-“. There’s a solution for that:

string number = "13-";
int parsed = int.Parse(number, NumberStyles.AllowTrailingSign);

“parsed” will be -13 as expected.

What if the string value has leading and trailing white space, like ” 13- “? Not a problem:

string number = " 13- ";
int parsed = int.Parse(number, NumberStyles.AllowTrailingSign | NumberStyles.AllowTrailingWhite | NumberStyles.AllowLeadingWhite);

“parsed” will be -13 again.

So far we’ve only looked at small numbers. Let’s go up to -13,000, i.e. ” 13,000- “. Here’s a solution:

string number = " 13,000- ";
int parsed = int.Parse(number, NumberStyles.AllowTrailingSign 
		| NumberStyles.AllowTrailingWhite 
		| NumberStyles.AllowLeadingWhite
		| NumberStyles.AllowThousands);

Note, however, that the above example will only work with cultures where thousands are delimited with a comma ‘,’, such as the US culture. We saw an example of that in the previous post where the currency symbol depended on the culture of the current thread. E.g. my PC is set to use the Swedish culture sv-SE. In Sweden thousands are not separated by a comma, but by a white space: “13 000”. The above code actually fails on my PC but the one below passes and “parsed” will be set to -13000:

string number = " 13 000- ";
int parsed = int.Parse(number, NumberStyles.AllowTrailingSign 
	| NumberStyles.AllowTrailingWhite 
	| NumberStyles.AllowLeadingWhite
	| NumberStyles.AllowThousands);

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 2

  1. Brian Dead Rift Webb says:

    Reblogged this on Brian By Experience.

Leave a Reply to Brian Dead Rift Webb Cancel 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 )

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: