views:

113

answers:

3

I need to make a number validation for specified string. The problem is, the string could be a large number, larger than any numeric type in C# can represent, so I can't use TryParse functions, because they will give only information about whether they can convert to those types.

It should take into account -/+, separator, and current culture settings.

I found some solutions using regular expressions, but all of them miss some details. And I'm not good at regular expressions

+8  A: 

You can use BigInteger if you are using C# 4.0 and the numbers are integers.

It Represents an arbitrarily large signed integer.

Use the TryParse method to avoid the possible exception from Parse (unless you are certain that the passed in string will always be a valid integer).

Oded
@Nick Martyshchenko - both `Parse` and `TryParse` will use the current culture settings. They also have overloads that specifically allow you to pass in a `IFormatProvider` such as a `CultureInfo`.
Oded
Am I miss something and `BigInteger` can store floating points?
Nick Martyshchenko
Isn't this an overkill approach when the OP just wants to validate the format?
Pieter
@Nick Martyshchenko - No, as the name suggests, it will only store Integers. The OP hasn't specified floats, however.
Oded
@Nick Martyshchenko - `culture settings` are respected by all the built it `Parse` and `TryParse` methods. I had read the question as meaning integers - you are right, he may have meant floats.
Oded
@Pieter - more overkill than RegEx?
Oded
Hmmmm. Got a point there. *Maybe* if his current app is not in .NET 4 and he would have to install .NET 4 on 1400 client computers, maybe it would be overkill.
Pieter
In that case he could use an open source implementation, such as: http://intx.codeplex.com/
Steven
+3  A: 

If you use .NET 4.0 you can use BigInteger. It contains a TryParse that excepts an IFormatProver that will do what you need. BigInteger has an unlimited size, so it is not possible that the numbers you need are larger than what BigInteger can handle.

Steven
A: 

Take a look at http://www.regexlib.com/Search.aspx?k=numeric&c=-1&m=5&ps=20. http://regexlib.com/ contains many examples of regular expressions, and there must be one that suits your requirements.

Pieter
Thanks for useful sources!
username