Culture invariant Decimal.TryParse()

Shaggydog picture Shaggydog · Apr 17, 2014 · Viewed 70.2k times · Source

I'm writing a custom string to decimal validator that needs to use Decimal.TryParse that ignores culture (i.e. doesn't care if the input contains "." or "," as decimal point separator). This is the suggested method:

public static bool TryParse(
    string s,
    NumberStyles style,
    IFormatProvider provider,
    out decimal result
)

I can't figure out what to use as the 3rd parameter. The examples I've seen look like this:

culture = CultureInfo.CreateSpecificCulture("en-GB");
Decimal.TryParse(value, style, culture, out number)

so they create a specific culture. CultureInfo does not have a "CreateInvariantCulture" method, and CultureInfo.InvariantCulture is not of the required type. What's the correct usage?

Answer

David Heffernan picture David Heffernan · Apr 17, 2014

In fact CultureInfo.InvariantCulture can be used here. The parameter expects IFormatProvider, an interface that CultureInfo implements. But InvariantCulture is invariant in the sense that it does not vary with the user's settings.

In fact, there is no culture that accepts either , or . as decimal separator – they are all one or the other. You'll have to find some other way to deal with data which can use either of these decimal separators.