Using NumberStyles to parse numbers in C# .NET Part 2
March 13, 2015 1 Comment
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.
Reblogged this on Brian By Experience.