Bartosz Cieszewski Bartosz Cieszewski - 1 month ago 15
C# Question

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.

Answer

It is because Replace method returns new string with replaced characters. It does not modify your original string.

So you need to reassign it:

kursS = kursS.Replace(",",".");