Validate currency amounts

I need to accept values which are valid amounts only. The application supports multiple locales so I need to accept amounts in the following formats:

10.05 or 10,05 (in some locale comma is used for decimal separator)

It should not accept values like 10.456 or 10,456

Users are not allowed to enter symbols like dollar, pound or euro. Also no comma separators allowed (for thousands, millions, billions, etc.). Also, no negatives amounts or zero value amounts are allowed.

Is there a built in .NET method to validate this? It is difficult to use regular expression as I need to allow either comma or dot for decimal separator based on the locale.

Answers


Take a look at the double.TryParse function that takes multiple parameters and in particular the NumberFormats enumeration. If you are specifying the correct culture, it can handle the comma versus decimal issue. I think you'll need tohandle the negative/zero issue separately though.


I would do the following:

  • replace , with .

  • if position of . in string < than stringlength-2 -> not accepted

  • parse to double, if fails -> not accepted


Use double.TryParse. It handles everything you want. You can provide a custom set of NumberStyles as well as a custom FormatProvider, if non fits your needs.


Need Your Help

Overall correlation in ggpairs with colour grouping?

r graphics ggplot2

This code produces a nice pairs plot that has a correlation read-out on the middle right:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.