String to Double Conversion (Comma to dot issue)

Struggling with the basics - I'm trying to code a simple currency converter. The XML provided by external source uses comma as a decimal separator for exchange rate (kurs_sredni):

<pozycja>
    <nazwa_waluty>bat (Tajlandia)</nazwa_waluty>
    <przelicznik>1</przelicznik>
    <kod_waluty>THB</kod_waluty>
    <kurs_sredni>0,1099</kurs_sredni>
</pozycja>

I already managed to load the data from XML into a nifty list of objects (kursyAktualne), and now i'm trying to do the math. I'm stuck with conversion.

First of all i'm assigning "kurs_sredni" to a string, trying to replace "," with "." and converting the hell out of it:

string kursS = kursyAktualne[iNa].kurs_sredni;
kursS.Replace(",",".");
kurs = Convert.ToDouble(kursS);
MessageBox.Show(kurs.ToString());

The messagebox show 1099 instead of expected 0.1099 and kursS still has comma, not dot.

Tried toying with some cultureInfo stuff i googled, but that was too random. I need to understand how to control this.

Jon Skeet
people
quotationmark

Just use decimal.Parse but specify a CultureInfo. There's nothing "random" about it - pick an appropriate CultureInfo, and then use that. For example:

using System;
using System.Globalization;

class Test
{
    static void Main()
    {
        var french = CultureInfo.GetCultureInfo("fr-FR");
        decimal value = decimal.Parse("0,1099", french);
        Console.WriteLine(value.ToString(CultureInfo.InvariantCulture)); // 0.1099
    }
}

This is just using French as one example of a culture which uses , as a decimal separator. It would probably make sense to use the culture of the origin of the data.

Note that decimal is a better pick for currency values than double - you're trying to represent an "artificial" construct which is naturally specified in base10, rather than a "natural" continuous value such as a weight.

(I would also be wary of a data provider who provides data in a non-standard format. If they're getting that wrong, who knows what else they'll get wrong. It's not like XML doesn't have a well-specified format for numbers...)

people

See more on this question at Stackoverflow