Here's my problem (for en-US):
Decimal.Parse("1,2,3,4")
returns 1234, instead of throwing an InvalidFormatException.
Most Windows applications (Excel en-US) do not drop the thousand separators and do not consider that value a decimal number. The same issue happens for other languages (although with different characters).
Are there any other decimal parsing libraries out there that solve this issue?
Thanks!
I ended up having to write the code to verify the currency manually. Personally, for a framework that prides itself for having all the globalization stuff built in, it's amazing .NET doesn't have anything to handle this.
My solution is below. It works for all the locales in the framework. It doesn't support Negative numbers, as Orion pointed out below, though. What do you guys think?
And here's one test to show it working (nUnit):
It is a common issue never solved by microsoft. So, I don't understand why 1,2,3.00 (english culture for example) is valid! You need to build an algorith to examine group size and return false/exception(like a failed double.parse) if the test is not passed. I had a similar problem in a mvc application, which build in validator doesn't accept thousands..so i've overwrite it with a custom, using double/decimal/float.parse, but adding a logic to validate group size.
If you want read my solution (it is used for my mvc custom validator, but you can use it to have a better double/decimal/float.parse generic validator) go here https://stackoverflow.com/a/41916721/3930528
You might be able to do this in a two-phase process. First you could verify the thousands separator using the information in the
CultureInfo.CurrentCulture.NumberFormat.NumberGroupSeparator
andCultureInfo.CurrentCulture.NumberFormat.NumberGroupSizes
throwing an exception if it doesn't pass and then pass the number into theDecimal.Parse()
;It's allowing thousands, because the default
NumberStyles
value used byDecimal.Parse
(NumberStyles.Number
) includesNumberStyles.AllowThousands
.If you want to disallow the thousands separators, you can just remove that flag, like this:
(the above code will throw an
InvalidFormatException
, which is what you want, right?)