Home > OS >  VB.NET Decimal.Try parse for dot and comma values
VB.NET Decimal.Try parse for dot and comma values

Time:09-16

I'm trying to parse string to decimal in vb.net which could contain dot or comma, for ex. '5000.00', '5000,00' (actually for Belgium and Niederlands). Code for decimal with dot:

Decimal.TryParse(amountStr, amountVal)

Code for decimal with comma:

Decimal.TryParse(amountStr, NumberStyles.AllowDecimalPoint, CultureInfo.CreateSpecificCulture("nl-BE"), amountVal)

Is it possible to combine these into one code without replacing comma in string?

CodePudding user response:

Is it possible to combine these into one code without replacing comma in string?

String-replacement is the "usual" solution to this problem. A slightly more elegant alternative would be to check if the string contains a . or a , and then provide the "correct" CultureInfo to TryParse:

Dim isBelgianFormat As Boolean = amountStr.Contains(",")

Dim ci As CultureInfo = If(isBelgianFormat,
                           CultureInfo.GetCultureInfo("nl-BE"),
                           CultureInfo.InvariantCulture)

...Decimal.TryParse(amountStr, NumberStyles.AllowDecimalPoint, ci, amountVal)...

This will also allow you to "fine-tune" your guessing logic by replacing the first line with a more complicated algorithm. (For example, this "simple" solution will fail if your users use thousands separators, i.e., if you want to correctly "guess" the value of both 500.000,00 and 500,000.00.)

That having been said, you can make your code more complicated to cover these cases as well, but how do you want to treat, for example, 500.000 or 500,000? Is it half a million or 500?

Thus, I urge you to reconsider your requirements. Especially when parsing monetary values, failing with a helpful error message is often preferable to guessing what the user might have meant.

  • Related