Advanced parsing using Int.TryParse in C#

Read Time:2 Minute, 42 Second

You have probably used the int.TryParse method with this signature:

That C# method accepts a string, s, which, if it can be parsed, will be converted to an int value and whose integer value will be stored in the result parameter; at the same time, the method returns true to notify that the parsing was successful.

As an example, this snippet:

prints 102.

Does it work? Yes. Is this the best we can do? No!

How to parse complex strings with int.TryParse

What if you wanted to parse 100€? There is a less-known overload that does the job:

As you see, we have two more parameters: style and provider.

IFormatProvider? provider allows you to specify the culture information: examples are CultureInfo.InvariantCulture and new CultureInfo("es-es").

But the real king of this overload is the style parameter: it is a Flagged Enum which allows you to specify the expected string format.

style is of type System.Globalization.NumberStyles, which has several values:

You can combine those values with the | symbol.

Let’s see some examples.

Parse as integer

The simplest example is to parse a simple integer:

Notice the NumberStyles style = NumberStyles.Integer;, used as a baseline.

Parse parenthesis as negative numbers

In some cases, parenthesis around a number indicates that the number is negative. So (100) is another way of writing -100.

In this case, you can use the NumberStyles.AllowParentheses flag.

Parse with currency

And if the string represents a currency? You can use NumberStyles.AllowCurrencySymbol.

But, remember: the only valid symbol is the one related to the CultureInfo instance you are passing to the method.

Both

and

are not valid. One because we are using English culture to parse Euros, the other because we are using Italian culture to parse Dollars.

Hint: how to get the currency symbol given a CultureInfo? You can use NumberFormat.CurrecySymbol, like this:

Parse with thousands separator

And what to do when the string contains the separator for thousands? 10.000 is a valid number, in the Italian notation.

Well, you can specify the NumberStyles.AllowThousands flag.

Parse hexadecimal values

It’s a rare case, but it may happen: you receive a string in the Hexadecimal notation, but you need to parse it as an integer.

In this case, NumberStyles.AllowHexSpecifier is the correct flag.

Notice that the input string does not contain the Hexadecimal prefix.

Use multiple flags

You can compose multiple Flagged Enums to create a new value that represents the union of the specified values.

We can use this capability to parse, for example, a currency that contains the thousands separator:

NumberStyles.AllowThousands | NumberStyles.AllowCurrencySymbol does the trick.

Conclusion

We all use the simple int.TryParse method, but when parsing the input string requires more complex calculations, we can rely on those overloads. Of course, if it’s still not enough, you should create your custom parsers (or, as a simpler approach, you can use regular expressions).

Are there any methods that have overloads that nobody uses? Share them in the comments!

Happy coding!

🐧

Source: https://www.code4it.dev/blog/advanced-int-tryparse

Tag Cloud

Java Java Logical Programs OTP Generation in Java python Recursion youtube video ASCII Upper and Lower Case blockchain javascript graph learn to code software development Successful Software Engineers breadth first search Java Array Programs Java Programs Uncategorized android ios programming kotlin web-development django data sql cybersecurity database swiftui serverless aws swift rust react background-position gradients loader mask grid nth-child pseudo elements indieweb WordPress Print Array without brackets C++ factorial Java String Programs Final Keyword Static Variable Axie Infinity Cryptokitties NFT games tool inserting MISC Tips Codes python code python projects python3 system info python project Bigginers How to Do Integrations Payment Gateways PHP checkout page in php Implement stripe payment gateway in Step by step in PHP integrate stripe gatway in php mysql payment gateway integration in php step by step payment gateway integration in php step by step with source code payment gateway integration in website PHP Integrate Stripe Payment Gateway Tutorial PHP shopping cart checkout code shopping cart in php stripe php checkout PHP/MySQL/JSON best international payment gateway does google pay accept international payments how to accept international payments in india paytm payment gateway razorpay codeigniter github razorpay custom checkout github razorpay get payment details razorpay integration in codeigniter github razorpay international payments Razorpay payment gateway integration in CodeIgniter razorpay payment gateway integration in php code Razorpay payment gateway integration with PHP and CodeIgniter Razorpay payment gateway setup in CodeIgniter Library & Frameworks Tips & Tricks UI/UX & Front-end coding birds online html code for google sign in login with google account in PHP login with google account using javascript login with google account using javascript codeigniter login with google account using php login with google account using php source code
How to Separate Production, Test and Development Resources in Azure Previous post How to Separate Production, Test and Development Resources in Azure
CSS-Tricks is joining DigitalOcean! Next post CSS-Tricks is joining DigitalOcean!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.