Search code examples
c#iformatprovider

Convert String to Double, Explicitly Using Period as Decimal Point


One of my software's functions is to convert numeric strings into double datatype. I want to explicitly indicate the use of period (.) as a decimal point. Thus, no matter the language settings of the user's system, it will correctly read a period-separated decimal. I believe the solution is to use the IFormatProvider argument in the Convert.ToDouble() function. I am unsure how to do this.

Example: String: "3.14" Double: 3.14


Solution

  • Use CultureInfo.InvariantCulture while parsing.

    double d = double.Parse("3.14", CultureInfo.InvariantCulture);
    

    See: CultureInfo.InvariantCulture Property

    The invariant culture is culture-insensitive; it is associated with the English language but not with any country/region.